How DRF undestand which field in serialazer.py is related to which model field?

imagine i have a super simple serializer.py file : enter image description here


and i just want to use it ! nothing special .. so im going to write something like this (with a model class called "Product") & its going to work : enter image description here


But how DRF undrstand which field in serializer.py file belongs to which field in the "Product" class in models file ? (i told DRF nothing about it !? + considering that the API Model != Data Model )

By default the "source field" is the same as the "target field". So it will map id to id, title to title, and unit_price to unit_price.

If you want to for example map name on the title field of the product, you can use the source=… parameter [drf-doc]:

class ProductSerializer(serializers.Serializer):
    id = serializer.IntegerField()
    name = serializer.CharField(max_length=255, source='title')
    unit_price = serializer.DecimalField(max_digits=6, decimal_places=2)

- When you use serializers.Serializer, DRF doesn’t link it to any model. It just matches the field names you define (like id, title, unit_price) to the attributes of the object you pass in (Product instance in your case).

- So even though DRF doesn’t "know" the model, it works because the field names match.

- If you want automatic mapping between the model and the serializer, use ModelSerializer

Just like this :

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'title', 'unit_price']

and then DRF knows which fields to use from the model.

Вернуться на верх