Django REST framework and creating two table entries from a POST form

后端 未结 1 1468
北海茫月
北海茫月 2021-01-24 20:08

I want to create entries in two tables (Log and Post) using the DRF Browseable API POST form.

The example below is contrived, but it outlines what I am trying to do.

相关标签:
1条回答
  • 2021-01-24 20:40

    From what I can tell you want to create a nested Log object. There are 2 ways of doing this:

    1. Send 2 POST Requests, One to create the Post, and the other to create the Log contained the received HTTP 200 data from the API.
    2. (Django and best way) Send the data all in one POST and parse it server side. Django Rest Framework takes care of this for you.

    I have changed your code so that it should work. Source

    class LogSerializer(serializers.ModelSerializer):                          
       class Meta:
            model = Log
            fields = ('ip', 'name')
    
    
    class PostSerializer(serializers.ModelSerializer):
        log = LogSerializer()
        class Meta:
            model = Post
            fields = ('info', 'log')
    

    views.py

    import generics
    
    class PostCreateAPIView(generics.CreateAPIView):
        model = Post
        serializer_class = PostSerializer
    

    Then you can send a POST Request containing 'info', 'ip', and 'name'.

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