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

Patricia Arquette
Release: 2024-11-11 20:52:02
Original
757 people have browsed it

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)
Copy after login

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__'
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template