이것은 Star
입니다. ListAPI 지금까지보기가 있습니다.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
(26) 및 (15)는 각각의 이미지 필드가 모두 콘텐츠 _이다 (outfit_img
라고 및 cloth_img
). 콘텐츠 _ 26 인 경우는이를 위해 내가의 콘텐츠 _ 예를 들어
에 따라 다른 시리얼을 사용하려면, OutfitListSerializer를 호출합니다. content_type이 15 인 경우 ClothListSerializer를 호출합니다.
이 링크 (def create_comment_serializer)의 도움을 받아이 Star
응용 프로그램을 구축 중입니다. (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 비교가 str (obj.content_type) == 'outfit'과 비교되어서 작동하지 않습니다. 그것은 작동하는 것 같았다 –