Django API Framework - Nested Models View

Viewed 221

I'm working on a Django API with the rest framework and i want to GET data of all child classes related to parent and also, the parent data. The only way i can do this right now is with the < depth = 1 > parameter inside the serializers. But the problem with this, is i get the parent data for every child, and i only want it once.

I have two nested models, let's say:

class Shop(models.Model):
   name = models.Charfield(max_length=50)
   address = models.Charfield(max_length=200)
   
   def __str__(self):
        return self.name
        
class Product(models.Model)
  shop = models.ForeignKey('Shop', on_delete=models.CASCADE , related_name='product')
  name = models.Charfield(max_length=50)
  price = models.IntegerField(default=0)       

Serializers look like this:

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = [
            'shop',
            'pk',   
            'name',
            'price',
        ]

class ShopProductSerializer(serializers.ModelSerializer):
    product_set = ProductSerializer(many=True)
    class Meta:
        model = Shop
        fields = [
            'shop',
            'pk',   
            'name',
            'price',
            'product_set',
            
        ]

so if i add depth=1 to the ProductSerializer i get the repeated Shop Data. I've seen this problem is solved by creating a nested serializer like the second one.

But then how do i addapt my API View to work with it?

Right now it looks like this:

class ProductListView(generics.ListAPIView):
    serializer_class    = ProductSerializer
    def get_queryset(self):
        shop  = self.kwargs['pk']
        products = Product.objects.filter(shop=shop)
        return products

My ideal JSON would look like this:

{
  'shop':{
    'name'    = 'abc',
    'address' = 'abc 123'
  },
  'products':{
    {
    ...product 1 data
    },
    {
    ...product 2 data
    }
  }
} 

1 Answers

install drf-writable-nested https://pypi.org/project/drf-writable-nested/

from rest_framework import serializers
from drf_writable_nested.serializers import WritableNestedModelSerializer
   

class ShopSerializer(serializers.ModelSerializer):
    class Meta:
        model = Shop
        fields = [  
            'name',
            'address'
        ]

class ProductSerializer(WritableNestedModelSerializer):
    shop = ShopSerializer()
    class Meta:
        model = Product
        fields = [
            'pk',
            'shop'
            'name'
            'price'
            ]

        
      
Related