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']
CodePudding user response:
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']
CodePudding user response:
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__'