Django REST Framework: when to create a hyperlinked resource and when nested resource? How to POST a nested resource?

后端 未结 1 1246
情书的邮戳
情书的邮戳 2021-02-14 10:57

I\'m building a REST web API using the Django REST Framework. Things are going great, but I have, however stumbled upon a problem with nested resources. At first, all relationsh

相关标签:
1条回答
  • 2021-02-14 11:38

    If i understood your question correctly, You want to have expanded author while you are retrieving the data and just want to send ID or URL in case of update and create.

    1# It is not about any guideline and it totally depends on your requirement of how your api is going to be used.

    2# So you need to extend your UserSerializer and override to_internal_value. Sample code might look like

    class MyCustomSerializer(UserSerializer):
        def to_internal_value(self, data):
            # data must be valid user-detail url
            return serializers.HyperLinkedRelatedField(queryset=User.objects.all(), view_name='user-detail').to_internal_value(data)
    

    Notice that you must have a Endpoint for user-detail in able to work with HyperLinkedRelatedField.

    So If you want to be able to send ID then sample code might look like

    class MyCustomSerializer(UserSerializer):
        # data must be valid user id
        def to_internal_value(self, data):
            return serializers.PrimaryKeyRelatedField(queryset=User.objects.all()).to_internal_value(data)
    

    However i would like to keep consistency in sending ForeignKey field in POST/PUT/PATCH. (Always Either URL or ID).

    then use it in your code like

    class PostSerializer(serializers.HyperlinkedModelSerializer):
        author = MyCustomSerializer()
    
        class Meta:
            model = Post
    

    Please see the documentation on Writable nested serializers to POST on a Nested resource.

    0 讨论(0)
提交回复
热议问题