Django REST框架,并从POST表单创建两个表项 [英] Django REST framework and creating two table entries from a POST form
问题描述
我想使用DRF可浏览API POST表单在两个表(日志和帖子)中创建条目。
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.
class Post(models.Model):
info = models.CharField()
class Log(TimeStampedModel):
ip = models.GenericIPAddressField(('IP Address'))
name = models.CharField()
data = models.ForeignKey(Post)
我想使用可浏览的API提交表单来创建一个日志条目。以下是序列化程序:
I want to use the browseable API to submit a form to create a Log entry. Here are the serializers:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('info',)
class LogSerializer(serializers.ModelSerializer):
data = serializers.Field()
class Meta:
model = Log
fields = ('ip', 'name', 'data')
上面的问题是 serializer.Field
是只读的,不会显示在POST表单上。如果我将其更改为CharField,它会显示,但是我收到一个错误,因为Post的一个实例不仅仅是Post对象的一个字段。
The problem with the above is that serializer.Field
is read only so does not show up on the POST form. If I change it to CharField it shows up, but then I get an error because an instance of a Post is expected not just a field of the Post object.
这里是我的观点:
class LogMixin(object):
queryset = Log.objects.all()
serializer_class = LogSerializer
class LogList(LogMixin, ListCreateAPIView):
pass
class LogDetail(LogMixin, RetrieveUpdateDestroyAPIView):
pass
这样做的正确方法是什么?
What's the correct way of doing this?
推荐答案
从我可以告诉你想要创建一个嵌套的Log对象。有两种方法:
From what I can tell you want to create a nested Log object. There are 2 ways of doing this:
- 发送2
POST
请求,一个创建Post,另一个创建日志包含从API接收的HTTP 200数据。 - (Django和最佳方式)将数据全部发送到一个
POST
并解析服务器端。 Django Rest Framework会为您处理这个问题。
- 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. - (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
然后你可以发送一个 POST
info','ip'和'name'。
Then you can send a POST
Request containing 'info', 'ip', and 'name'.
这篇关于Django REST框架,并从POST表单创建两个表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!