我有两个模型,BookTicket
和Ticket
。
class BookTicket(models.Model):
user = models.ForeignKey(User)
booking_ref = models.CharField(max_length=25, blank=True)
class Ticket(models.Model):
seat = models.ForeignKey(Seat)
user = models.ForeignKey(User)
show = models.ForeignKey(Show)
booking_ref = models.ForeignKey(BookTicket)
这是来自客户端的数据
[
{u'seat': 49, u'user': 3, u'show': 2},
{u'seat': 50, u'user': 3, u'show': 2}
]
我想要做的是,如果序列化is_valid
,则创建一个新的预订对象,并将该对象更新为所有故障单数据的booking_ref
。
def buy_ticket(request):
serialized = TicketSerializer(data=request.data, many=True)
if serialized.is_valid():
...
b = BookTicket.objects.create(user=request.user)
...
... update all of the data's booking_ref with newly created booking instance i.e., b
...
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
我该怎么做?
答案 0 :(得分:2)
您可以将b
作为save
方法(docs)的参数传递。这将为新票证添加booking_ref
:
serialized = TicketSerializer(data=request.data, many=True)
if serialized.is_valid():
b = BookTicket.objects.create(user=request.user)
serialized.save(booking_ref=b)