[Django]-Add Serializer on Reverse Relationship – Django Rest Framework

37πŸ‘

βœ…

Ahmed Hosny was correct in his answer. It required the many parameter to be set to True to work.

So final version of the CartSerializer looked like this:

class CartSerializer(serializers.ModelSerializer):
    cartitem_set = CartItemSerializer(read_only=True, many=True) # many=True is required
    class Meta:
        model = Cart
        depth = 1
        fields = (
            'id', 
            'date_created', 
            'voucher', 
            'carrier', 
            'currency', 
            'cartitem_set', 
        )
πŸ‘€Marcus Lind

13πŸ‘

It’s important to define a related name in your models, and to use that related name in the serializer relationship:

class Cart(models.Model):
   name = models.CharField(max_length=500)

class CartItem(models.Model):
   cart = models.ForeignKey(Cart, related_name='cart_items')
   items = models.IntegerField()

Then in your serializer definition you use those exact names:

class CartSerializer(serializers.ModelSerializer):
    cart_items = CartItemSerializer(read_only=True)
    class Meta:
       model = Cart
       fields = ('name', 'cart_items',)
πŸ‘€djq

0πŸ‘

It would be wise to share your whole code, that is model and serializers classes. However, perhaps this can help debug your error,

My serializer classes

class CartItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = CartItem
        fields = ('id')

class CartSerializer(serializers.ModelSerializer):

    #take note of the spelling of the defined var
    _cartItems = CartItemSerializer()
    class Meta:
        model = Cart
        fields = ('id','_cartItems')

Now for the Models

class CartItem(models.Model):
    _cartItems = models.ForeignKey(Subject, on_delete=models.PROTECT)
    #Protect Forbids the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT.
class Meta:
    ordering = ('id',)

class Cart(models.Model):
    class Meta:
    ordering = ('id',)

For a detailed overview of relationships in django-rest-framework, please refer their official documentation

πŸ‘€ChampR

Leave a comment