Home  >  Article  >  Backend Development  >  How to Assign Foreign Keys in Nested Serializers with Django REST Framework?

How to Assign Foreign Keys in Nested Serializers with Django REST Framework?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 20:52:02731browse

How to Assign Foreign Keys in Nested Serializers with Django REST Framework?

DRF: Simple Foreign Key Assignment with Nested Serializers

Within Django REST Framework, a standard ModelSerializer permits assignment or modification of ForeignKey model relationships via POSTing an ID as an integer. However, extracting this behavior from a nested serializer can be a challenge.

Simplest Nested Serializer Approach

DRF doesn't inherently provide this functionality, necessitating a custom serializer field:

from rest_framework import serializers

class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField):
    def __init__(self, **kwargs):
        # Serializer for this field
        self.serializer = kwargs.pop('serializer', None)
        if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer):
            raise TypeError('"serializer" is not a valid serializer class')

        super().__init__(**kwargs)

    def use_pk_only_optimization(self):
        # Avoid using PK optimization if a serializer is provided
        return False if self.serializer else True

    def to_representation(self, instance):
        # Use provided serializer or default representation
        if self.serializer:
            return self.serializer(instance, context=self.context).data
        return super().to_representation(instance)

In your parent serializer, employ this new field as follows:

class ParentSerializer(ModelSerializer):
    child = RelatedFieldAlternative(queryset=Child.objects.all(), serializer=ChildSerializer)

    class Meta:
        model = Parent
        fields = '__all__'

With this generic approach, you can readily handle multiple serializers with this functionality.

Method to Override to_representation()

Alternatively, overriding the to_representation() method of the parent serializer also achieves this goal:

class ParentSerializer(ModelSerializer):
    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['child'] = ChildSerializer(instance.child).data
        return response

This method requires defining different fields for creation and reading, which may not be ideal.

The above is the detailed content of How to Assign Foreign Keys in Nested Serializers with Django REST Framework?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn