Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework return selected field in view

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?

like image 285
Agus Avatar asked Apr 10 '13 03:04

Agus


1 Answers

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.

like image 80
Tom Christie Avatar answered Nov 12 '22 05:11

Tom Christie