简体   繁体   中英

How to list all objects from particular model in django rest framework?

I have two models :

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(default=0, decimal_places=2, max_digits=10)

    def __str__(self):
        return self.name
class Receipt(models.Model):
    purchase_date = models.DateTimeField(auto_now=True, null=False)
    shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True)
    products = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return super().__str__()

My receipt url looks like this: 在此处输入图像描述

And i would like it to show list of all products, instead of a number of them. How to do this?

My viewsets:

class ReceiptViewSet(viewsets.ModelViewSet):
    queryset = Receipt.objects.all()
    serializer_class = ReceiptSerializer
    permission_classes = [AllowAny]

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    permission_classes = [AllowAny]
    enter code here

serializers:

class ProductSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'price']

class ReceiptSerializer(serializers.HyperlinkedModelSerializer):
    products = serializers.PrimaryKeyRelatedField(read_only=True)

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

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']

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__'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM