merry-go-round
merry-go-round

Reputation: 4625

List models according to ContentType and object_id. (How to List Generic ForeignKey objects)

This is Star ListAPIView so far I have.

[
    {
        "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
    }
]

Since content_type of the very first object in the array is 26, its referring object is 'Outfit'. For better understanding, I'm providing Star Model. It contains ContentType and object_id field. It uses two fields to refer Generic 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()

And here is Serializer and View

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

Both content_type 26 and 15 have each image fields (called outfit_img and cloth_img) for each. To Achieve this, I want to use different Serializer depending on the content_type

For example, if content_type is 26, call OutfitListSerializer. If content_type is 15, call ClothListSerializer.

I'm building this Star app having help from this link (def create_comment_serializer). (https://github.com/codingforentrepreneurs/Blog-API-with-Django-Rest-Framework/blob/master/src/comments/api/serializers.py).

Thank you so much!

Upvotes: 0

Views: 486

Answers (1)

user8060120
user8060120

Reputation:

if i understand you, may be you can use serializermethodfield serializers.py

class ListStarSerializer(serializers.ModelSerializer):
    img_data = serializers.SerializerMethodField()

    class Meta:
        model = Star
        fields = ('user', 'content_type', 'object_id')

   def get_img_data(self, obj):
      if obj.content_type_id == 15:
          serializer = ClothListSerializer(obj.content_object)
      elif obj.content_type_id == 26:
          serializer = OutfitListSerializer(obj.content_object)
      else:
          return {}
      return serializer.data

Upvotes: 1

Related Questions