我正在尝试重写保存方法,以便在创建一个模型时,创建第二个模型的实例。但是,看起来我尝试创建的辅助模型(本例中为 Restaurant
)被创建了两次。这是为什么?
模型.py
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self):
return "%s the place" % self.name
def save(self, *args, **kwargs):
super(Place, self).save(*args, **kwargs)
if Restaurant.objects.filter(place=self).count() == 0:
restaurant = Restaurant.objects.create(place=self)
class Restaurant(models.Model):
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
primary_key=True,
)
最佳答案
您的保存方法没有正确的缩进。我认为这是剪切和粘贴时的错误。在该方法中。
if Restaurant.objects.filter(place=self).count() == 0:
restaurant = Restaurant.objects.create(restaurant=self)
这本质上就是get_or_create确实如此,但以原子方式进行。
This method is atomic assuming correct usage, correct database configuration, and correct behavior of the underlying database. However, if uniqueness is not enforced at the database level for the kwargs used in a get_or_create call (see unique or unique_together), this method is prone to a race-condition which can result in multiple rows with the same parameters being inserted simultaneously.
当然,您可以在自己的代码中使用原子 block 执行相同的操作,但为什么要麻烦呢。就这么做
Restaurent.objects.get_or_create(place=self)
这不是 place=self
而不是您保存方法中的 restaurent=self
吗?
关于python - Django save 方法调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37622071/