我对Django还是很陌生,并且对模型有疑问。
class RestaurantAvailability(models.Model):
"""RestaurantAvailability Model"""
DayTime = models.DateTimeField()
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
availability = models.IntegerField(null=True)
def __str__(self):
"""What to show when we output an object as a string."""
restaurant = self.restaurant.name
time = self.DayTime
return restaurant + " " + str(time)
class Reservation(models.Model):
"""Reservation Model"""
name=models.CharField(max_length=100)
email=models.CharField(max_length=100)
note=models.CharField(max_length=100)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
restaurantAvailability = models.ForeignKey(RestaurantAvailability, on_delete=models.CASCADE)
def __str__(self):
"""What to show when we output an object as a string."""
person = self.name
place = self.restaurant.name
time = self.restaurantAvailability.DayTime
return person + " " + place + " " + str(time)
def save(self, *args, **kwargs):
"""decrement resturant avalability by 1 on create"""
if not self.pk:
print('|||||||||||||||||||||||||||||||||||||||||')
print(self.restaurantAvailability.availability)
print('|||||||||||||||||||||||||||||||||||||||||')
self.restaurantAvailability.availability -= 1 # decrement resturant avalability by 1 on create
print(self.restaurantAvailability.availability)
super(Reservation, self).save(*args, **kwargs)
当我创建一个新的预留时,我想将Resturant的可用性递减1。之所以运行save方法是因为我成功创建了一个新的保留,并且甚至在递减后也打印出了正确的可用性。但是,当我进入管理面板查看RestaurantAvailability时,可用性没有任何变化。好像没有保存可用性。
我的问题是创建新对象时如何更新外键上的字段?
答案 0 :(得分:1)
更改可用性后,需要保存可用性。注意self.restaurantAvailability.save()
行。您也可以执行update
语句而不是调用.save()
或将该逻辑移至信号。
def save(self, *args, **kwargs):
"""decrement resturant avalability by 1 on create"""
if not self.pk:
print('|||||||||||||||||||||||||||||||||||||||||')
print(self.restaurantAvailability.availability)
print('|||||||||||||||||||||||||||||||||||||||||')
self.restaurantAvailability.availability -= 1 # decrement resturant avalability by 1 on create
self.restaurantAvailability.save()
print(self.restaurantAvailability.availability)
额外:可能值得考虑制作transaction atomic,这样您就不会遇到并发请求的问题。
from django.db import models, transaction
@transaction.atomic
def save(self, *args, **kwargs):
...
答案 1 :(得分:1)
您应该使用post_save
signal handler处理此问题。
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Reservation, dispatch_uid="update_availability")
def update_stock(sender, instance, **kwargs):
RestaurantAvailability.objects.filter(pk=instance.restaurantAvailability_id).update(availability=F('availability') - 1)
您仍然需要担心并发请求产生的预留量超出处理能力。