我的模板中有一个按钮来更改/更新数据库中的ForeignKey对象。
但是,应更新的对象不会更改。
如何更新数据库中的ForeignKey对象?
Views.py
if 'order' in request.POST:
status_change = request.POST['order']
order = Order.objects.get(pk = status_change)
if order.orderstatus.ORDERSTATUS == 'Received':
order.orderstatus.ORDERSTATUS='Requested'
order.save()
elif order.orderstatus.ORDERSTATUS == 'Requested':
order.orderstatus.ORDERSTATUS = 'Completed'
order.save()
elif order.orderstatus.ORDERSTATUS == 'Completed':
order.orderstatus.ORDERSTATUS = 'Canceled'
order.save()
else:
order.orderstatus.ORDERSTATUS = 'Received'
order.save()
Models.py
RECEIVED = 'Received'
REQUESTED = 'Requested'
CANCELED = 'Canceled'
COMPLETED = 'Completed'
ORDER_STATUS = (
(RECEIVED , 'Received'),
(REQUESTED, 'Requested'),
(CANCELED, 'Canceled'),
(COMPLETED, 'Completed'),
)
class Order(models.Model):
orderstatus = models.OneToOneField(OrderStatus, on_delete=models.CASCADE)
class OrderStatus(models.Model):
ORDERSTATUS = models.CharField(
max_length = 10,
choices = ORDER_STATUS,
default = RECIEVED,
)
答案 0 :(得分:0)
order.orderstatus
是它自己的数据库模型,而save
不会跨越外键,所以你应该这样做:
order.orderstatus.save()
而不是:
order.save()