[Answered ]-Creating a Serialiser for a Reverse Generic Relationship

2👍

Create a GenericRelation on your Page model for example:

class Page(models.Model):
     title = models.CharField(max_length=80)
     stuff = GenericRelation('app_name_model_here')

Then used your nested serializer like this…

class PageSerializer(serializers.ModelSerializer):
    stuff = YOURColltionserializer(many=True)
    class Meta:
        model = Page
        fields = ("title", "stuff" )

Once you have defined your YOURColltionserializer this will work as excepted.

0👍

First of all, your JSON is incorrect, the propher way is something like this:

{
   "results":[
      {
         "url":"http://127.0.0.1:8000/v1/page/00c8015e-9b03...",
         "title":"Test Page",
         "collections":{
            "title":"Test Collection",
            "collection_items":[
               {
                  "image":"http://www.demo.com/test.png",
                  "video":null
               },
               {
                  "image":null,
                  "video":"http://www.demo.com/test.mpeg"
               }
            ]
         }
      }
   ]
}

To achieve this You should define serializer like this:

class CollectionItemSerializer(serializers.ModelSerializer):
    class Meta:
       model = CollectionItem
       fields = ['image', 'video']

class CollectionSerializer(serializers.ModelSerializer):
    collection_items = CollectionItemSerializer(many=True, read_only=True)
    class Meta:
       model = Collection
       fields = ['title', 'collection_items']

class PageSerializer(serializers.Serializer):
    title = serializes.CharField(max_length=200)
    url = serializers.SerializerMethodField()
    collections = CollectionSerializer(many=true, read_only=True)

    def get_url(self, obj):
        return self.context.request.path_info

class ResultSerializer(serializers.Serializer):
    result = PageSerializer(read_only=True)

Then in your view:

page = Page.objects.get(...)
collections = Collection.objects.filter(...)
result = {
    'title': page.title, 
    'collections':collections
}

serializer = ResultSerializer(
   {'result':result},
    context={'request': request}
}
return Response(serializer.data)
👤WBAR

Leave a comment