Home > other >  how to serialize two classes have one to many relation in django
how to serialize two classes have one to many relation in django

Time:07-27

this is my models

  class Users(models.Model) :
        name = models.CharField(max_length=20 , blank=False , null=False)
        email = models.EmailField(max_length=50 , blank=True , null=True)
        password = models.CharField(max_length=30 , blank=False , null=False)
        birthday = models.DateField(null=False)
        photo = models.ImageField(upload_to = 'user_photos/%y/%m/%d')
        #friend = models.ManyToManyField('self',through='Notif',null=True,related_name='friend')
     
    
    class Product(models.Model):
        pub_date = models.DateTimeField(default=datetime.now)
        price = models.DecimalField(max_digits=100000,decimal_places=5,null=False,blank=False)
        size = models.IntegerField(null=True,blank=True,default='undefined')
        photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True)
        #for 1--n relation with users
        user_id = models.ForeignKey(Users,on_delete=models.CASCADE,null=True,related_name='user')

this is my serializers.py

class ProductSerializer (serializers.ModelSerializer):
    class Meta :
        model = Product
        fields = '__all__'

class UsersSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = '__all__'

i want to send product object with the email of his user what i have to do in serializers and views to make it note i use function based views in my views

CodePudding user response:

First of all, you should change user_id to user.

in serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = ['id','email']

class ProductSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta :
        model = Product
        fields = '__all__'

in function based views:

def get_product(request,product_id):
    instance = Product.objects.select_related('user').get(id=product_id)
    serializer = ProductSerializer(instance)
    return Response(serializer.data)

NOTE: select_related is used to get product with user at the same query (join query).

  • Related