Implementing Serializer relations
Django models have three types of relational fields – ForeignKey
, ManyToManyField
, and OneToOneField
(all of them support reverse relationships too). So far, we have learned how to use model serializers efficiently, but let’s now explore how we can work with related fields in Serializers.
By default, when a model has any related field, ModelSerializer
will link the associated field to PrimaryKeyRelatedField
in the serializer definition. A DRF serializer will use PrimaryKeyRelatedField
for all kinds of related field serializers, with different options passed.
Here, we will learn how to create related field serializers:
- For
ForeignKey
, the DRF model serializer assignsPrimaryKeyRelatedField
to the serializer - For
OneToOneField
, the DRF model serializer assignsPrimaryKeyRelatedField
to the serializer with an additionalUniqueValidator
attached - For
ManyToManyField
, the DRF model serializer assignsPrimaryKeyRelatedField...