Let's say I have a model name Book. I have two views(list and detail)
models.py
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publishdate = models.DateTimeField()
serializers.py
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
If I'm going to use this serializer in my list view and detail view. Can I set the return field? Example : list view only return name list only and detail view will return name, author, publishdate field. Or do I have to create new serializer and insert fields in Class Meta on both class?
If you need different representations for list and detail views you should define seperate serializers for each. For example...
class DetailBookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name', 'author', 'publishdate')
class ListBookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name',)
Then make sure to set the serializer_class
attribute as appropriate on each view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With