這是Star
ListAPIView到目前爲止,我。根據ContentType和object_id列出模型。 (如何列出通用ForeignKey的對象)
[
{
"user": 1,
"content_type": 26,
"object_id": 7
},
{
"user": 1,
"content_type": 26,
"object_id": 8
},
{
"user": 1,
"content_type": 15,
"object_id": 5
},
{
"user": 1,
"content_type": 15,
"object_id": 6
}
]
由於數組中第一個對象的content_type爲26,所以它的引用對象是'Outfit'。爲了更好地理解,我提供Star
型號。它包含ContentType和object_id字段。它使用兩個字段來指代通用 foreignKey。
class Star(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
objects = StarManager()
這裏是串行器和查看
serializers.py
class ListStarSerializer(serializers.ModelSerializer):
class Meta:
model = Star
fields = ('user', 'content_type', 'object_id')
views.py
class StarListAPIView(generics.ListAPIView):
serializer_class = ListStarSerializer
def get_queryset(self):
qs = Star.objects.filter(user=self.request.user)
return qs
兩個CONTENT_TYPE 26和15的每個圖像區域(稱爲outfit_img
和cloth_img
)。要做到這一點,我想用這取決於CONTENT_TYPE
例如不同的序列化,若CONTENT_TYPE是26,撥打OutfitListSerializer。如果content_type是15,則調用ClothListSerializer。
我從這個鏈接建設這個有幫助Star
應用程序(DEF create_comment_serializer)。 (https://github.com/codingforentrepreneurs/Blog-API-with-Django-Rest-Framework/blob/master/src/comments/api/serializers.py)。
非常感謝!
它幾乎工作,但我認爲我們應該傳遞一個參數兩者OutfitSerializer和ClothSerializer。其實img_data返回'{}' –
是的,它解決了錯誤。不是它說'utf-8'編解碼器不能解碼位置0中的字節0xff:無效的起始字節。現在我正在尋找解決方案:)我想這是關於一些奇怪的錯誤蟒比較 –
== obj.content_type 15沒有工作,所以我比較它爲海峽(obj.content_type)==「裝」。它似乎工作 –