Andy
Andy

Reputation: 738

Django REST ModelSerializer --- General Question

I am working through a tutorial that includes the building of an articles app. I have an Article model that I am serializing and I am curious about why I need to explicitly set certain fields when using a ModelSerializer.

Here is my model:

from django.db import models

from core.models import TimestampedModel


class Article(TimestampedModel):
    slug            = models.SlugField(db_index=True, max_length=255, unique=True)
    title           = models.CharField(db_index=True, max_length=255)
    description     = models.TextField()
    body            = models.TextField()
    author          = models.ForeignKey('profiles.Profile', on_delete=models.CASCADE, related_name='articles')

    def __str__(self):
        return self.title

Pretty standard stuff. Next step is to serialize the model data in my serializers.py file:

class ArticleSerializer(serializers.ModelSerializer):
    author = ProfileSerializer(read_only=True) # Three fields from the Profile app
    description = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)

    class Meta:
        model = Article
        fields = (
        'author',
        'body',
        'createdAt',
        'description',
        'slug',
        'title',
        'updatedAt',
    )

Specifically, why do I need to explicitly state the author, description, and slug fields if I am using serializers.ModelSerializer and pulling those fields in from my model in my class Meta: below?

Thanks!

Upvotes: 0

Views: 710

Answers (2)

alexyichu
alexyichu

Reputation: 3622

In the Django-Rest-Framework documentation, drf-docs/model_serializer/specifying-which-fields-to-include it says:

If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm. It is strongly recommended that you explicitly set all fields that should be serialized using the fields attribute. This will make it less likely to result in unintentionally exposing data when your models change.

Therefore by using fields = in the Serializer META, you can specify just the needed fields, and not returning vital fields like id, or exessive information like updated and created timestamps.

You can also instead of using fields, use exclude, which again takes in a tuple, but just excludes the fields you don't want.

These are especially useful when your database table contains a lot of information, returning all this information, especially if it is listed, can result in large return JSON's, where the frontend may only use a small percentage of the sent data.

DRF has designed their framework like this to specifically combat these problems.

Upvotes: 1

Ngoc Pham
Ngoc Pham

Reputation: 1458

In my opinion, we should define field in serializer for:

  • Your api use serializer don't need all data of your models. Then you can limit field can get by serializer. It faster if you have so much data.
  • You dont want public all field of your model. Example like id
  • Custom field in serializer like serializers.SerializerMethodField() must define in fields for work

Finally, iF you dont want, you can define serializer without define fields. Its will work normally

Upvotes: 0

Related Questions