在Django和Django Rest Framework中使用一个请求创建多个对象 [英] Creating multiple objects with one request in Django and Django Rest Framework
问题描述
我正在使用Django作为后端服务器,并使用Vue.js作为前端Movie应用程序.
I am using Django as the backend server and Vue.js for the front end Movie app.
我有一个票务模型
class MovieTicket(models.Model):
show = models.ForeignKey(Show)
seat = models.ForeignKey(Seat)
user = models.ForeignKey(User)
purchased_at = models.DateTimeField(default=timezone.now)
qrcode = models.ImageField(upload_to='qrcode', blank=True, null=True)
qrcode_data = models.CharField(max_length=255, unique=True, blank=True)
class Meta:
unique_together = ('show', 'seat')
及其相关的序列化器
class MovieTicketSerializer(serializers.ModelSerializer):
class Meta:
model = MovieTicket
fields = '__all__'
要购买新票证,有一个视图映射到此URL http://dev.site.com/api/movies/buy-ticket/:
To buy a new Ticket there's a view which is mapped to this url http://dev.site.com/api/movies/buy-ticket/:
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def buy_ticket(request):
serialized = MovieTicketSerializer(data=request.data)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
现在从前端(Vue.js),我可以创建一个新的电影票:
Now from the front end (Vue.js) I can create a new movie ticket:
const formBody = {
show: this.$store.state.showSelected.showTime.id,
user: this.$store.state.user.id,
// selectedSeats is an array of seats that have been selected by the user. Here I am passing the first seat object.
seat: this.$store.state.selectedSeats[0].seat.id
};
this.$http.post("http://dev.site.com/api/movies/buy-ticket/", formBody)
.then(function (response) {
console.log(response.data);
})
.catch(function (response) {
console.log(response);
});
return;
如果表单有效,则将创建一个新的MovieTicket对象,否则显示错误.
If the form was valid, this will create a new MovieTicket Object, or else show the error/s.
现在,假设用户选择了多个席位,我可以遍历每个 selectedSeats
数组,并在客户端获取席位ID.然后发布这样的内容:
Now, suppose if the user selected multiple seats, I can loop through each selectedSeats
array and get the seat ids on the client side. And post something like this:
{
"purchased_at": null,
"qrcode": null,
"qrcode_data": "",
"show": 11,
"seat": [
106,
219
],
"user": 34
}
但是我很困惑的是,如果Django rest框架每个请求只接受一个席位,并相应地显示错误,该如何传递多个
But what I am confused is how can I pass multiple seat.id
if Django rest framework is only accepting one seat per request and display errors accordingly? Meaning display errors if a ticket is available or not, and if its available create movie tickets for that show-seat.
推荐答案
使用many = True初始化序列化程序
Init the serializer with many=True
在您的实现中,这确实很容易实现:
In your implementation this is really easy to accomplish:
serialized = MovieTicketSerializer(data=request.data, many=True)
数据不是单个对象,而是对象的数组.
Data is no single object but an array of objects.
您的信息建议您需要转换request.data以使那些多个对象(所有相同数据只是不同的座位号).对吧?
Your infos suggest that you need to transform request.data to make those multiple objects (all the same data just different seat number). Right?
无论如何:
请参阅:如何创建多个Django Rest Framework创建模型实例?
此处是drf文档中的信息: http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects
here the info in the drf docu: http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects
(强烈建议您在编写第一个真正的实现之前,从头到尾阅读drf文档,并开始使用它.有许多种使用drf的方法,并且知道所有这些都会导致更好的决策)
(highly suggest to read the drf docs from top to bottom and just playing around with it, before coding your first real implementation. there are many ways to use drf, and knowing all of them leads to better decisions)
编辑2(问题更新后):
EDIT 2 (after question update):
您可以从客户端发送此JSON(请参见下文),也可以在调用 MovieTicketSerializer(之前)从客户端通过
: buy_ticket(request)
方法发送的当前JSON创建此格式...,many = True)
You could send this JSON from the client (see below), or create this format from the current JSON the client sends in your buy_ticket(request)
method before you call MovieTicketSerializer(...,many=True)
:
[
{
"purchased_at": null,
"qrcode": null,
"qrcode_data": "",
"show": 11,
"seat": 106,
"user": 34
},
{
"purchased_at": null,
"qrcode": null,
"qrcode_data": "",
"show": 11,
"seat": 219,
"user": 34
}
]
这篇关于在Django和Django Rest Framework中使用一个请求创建多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!