Toshi023Yuki
Toshi023Yuki

Reputation: 345

When don't we use "__all__" in ModelSerializer in Django Rest Framework

This is just my curiosity but I will be very happy if anyone answers my question.

I am using Django Rest Framework but I'm a beginner. In serializers.py, I use ModelSerializer and "all" to fields attribute. This is an example.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

And then, I just thought

when don't we use "__all__" in serializers.py??

As long as we create models.py in advance, I think we usually use all fields in each Model. I would like you to teach me when we omit specific fields that come from each Model.

Thank you.

Upvotes: 2

Views: 2122

Answers (2)

user1600649
user1600649

Reputation:

So the second question is a bit harder to explain in a comment:

If we use some fields of all fields in Model, how do we store information of the rest of fields?

Various cases:

Fields with defaults:


class Log(models.Model):
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

class LogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Log
        fields = ('message',)

For autogenerated, think user profile models via the post_save signal or calculated fields:

class OrderLine(models.Model):
    order = models.ForeignKey(Order)
    name = models.CharField(max_length=200)
    quantity = models.IntegerField()
    price = models.DecimalField()

class OrderLineSerializer(serializers.ModelSerializer):
    order = serializers.PrimaryKeyRelatedField()
    product = serializers.IntegerField()
    class Meta:
        model = OrderLine
        fields = ('quantity', 'product', 'order')

In this case, the product is a primary key for a product. The serializer will have a save method that looks up the product and put it's name and price on the OrderLine. This is standard practice as you cannot reference a product in your orders, else your orders would change if you change (the price of) your product.

And derived from request:

class BlogPost(models.Model):
    author = models.ForeignKey(User)
    post = models.TextField()

class BlogPostSerializer(serializers.ModelSerializer):
    class Meta:
        model = BlogPost
        fields = ('post',)

    def create(self, validated_data):
        instance = BlogPost(**validated_data)
        instance.author = self.context['request'].user
        instance.save()
        return instance

This is pretty much the common cases.

Upvotes: 2

HuLu ViCa
HuLu ViCa

Reputation: 5452

There are many cases, but I think the two main ones are:

  • When you don't want all fields to be returned by the serializer.

  • When you need some method of the serializer to know its fields. In such case, you should traverse fields array, but it doesn't work if you use __all__, only if you have an actual list of fields.

Upvotes: 0

Related Questions