[Answered ]-How to list all objects from particular model in django rest framework?

1👍

You can simply specify nested representations using the depth option

Give this a try

class ReceiptSerializer(serializers.HyperlinkedModelSerializer):
    ... 

    class Meta:
        model = Receipt
        fields = ['id', 'purchase_date', 'shop', 'products']
        depth = 1

Otherwise

class ReceiptSerializer(serializers.HyperlinkedModelSerializer):
    products = ProductSerializer(many=True, read_only=True)
    ... 

    class Meta:
        model = Receipt
        fields = ['id', 'purchase_date', 'shop', 'products']

0👍

I have tried Sumithran ‘s solution but i made a small adjustment, rather than using
serializers.HyperlinkedModelSerializer i used serializers.ModelSerializer and it displayed the products as follows View

Hope it answers what you are looking for 🙂

from rest_framework import serializers

class ReciptSerializer(serializers.ModelSerializer):
    class Meta:
        model = Receipt
        fields = ['id', 'purchase_date', 'shop', 'products']
        depth = 1

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

Leave a comment