python - Django save 方法调用了两次?

标签 python django

我正在尝试重写保存方法,以便在创建一个模型时,创建第二个模型的实例。但是,看起来我尝试创建的辅助模型(本例中为 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/

相关文章:

django - 如何使用查询集缓存优化 django Admin

django - 如何在 Django simple jwt 中为 Web 和移动应用程序设置不同的到期时间?

python - Django 。对 Viewset 的 @link 或 @action 方法进行分页

python - 在 python tkinter 中处理异常

python - 如何在数组内执行双重排序?

python - Django 从模型返回特定字段作为外键

python - 捕获任何 DoesNotExist 错误

django - 使用 Django session 存储登录用户

python - 使用 Python 解析和拆分 .txt 文件并导出为 .csv 行

python - 根据另一列的条件创建 Pandas 列