python - Django OneToOneField 允许在线引用

标签 python django model

我正在尝试创建一对一的引用,并希望确保该引用不允许用于其他模型或实例。

例如

假设我有一个地址模型、人员模型和公司模型

人员有一个要寻址的 OneToOneField 字段 公司还有一个 OneToOneField 字段用于地址

address=Address(data="some address")
company=Company(name="some company",address=address)
person=Person(name="my name",address=address)

型号:

class Address(models.Model):
  data = models.CharField(max_length=255, blank=True, null=True)
class Company(models.Model):
  name = models.CharField(max_length=255, blank=True, null=True)
  address=models.OneToOneField(Address,on_delete=models.CASCADE)
class Person(models.Model):
  name = models.CharField(max_length=255, blank=True, null=True)
  address=models.OneToOneField(Address,on_delete=models.CASCADE)

我希望系统对此抛出错误,因为我将相同的地址设置为 2 个不同的模型。

此外,如果我删除地址,这将同时删除个人和公司。

通常你会用代码来捕获这个问题,而不会犯这样的愚蠢错误。 但是系统可以捕获它,因为它是一对一的吗?

最佳答案

在删除的情况下,您可以使用on_delete=models.PROTECT。在另一种情况下,您可以添加 unique=True ,这样 id = 1 的人员将具有 id = 1 的地址, id = 2 的人员不能再具有 id = 1 的地址。但它只能解决一种模型:
address=models.ForeignKey(Address, unique=True, on_delete=models.PROTECT)

一种新方法是创建一个模型来引用公司和个人的地址,并能够禁止使用相同地址 ID 进行创建:

class AddressExample(models.Model):
    id_address = models.ForeignKey(Address, unique=True,on_delete=models.PROTECT)
    id_person = models.ForeignKey(Person, blank=True, null=True, unique=True, on_delete=models.PROTECT)
    id_company = models.ForeignKey(Person, blank=True, null=True, unique=True, on_delete=models.PROTECT)  

请注意,我使用了 blank=True, null=True,因此您可以仅使用个人或公司创建实例,而无需使用两者创建实例。还有一个 Meta 可以使用主键组合。

class AddressExample(models.Model):
    id_address = models.ForeignKey(Address, unique=True,on_delete=models.PROTECT)
    id_person = models.ForeignKey(Person, blank=True, null=True, unique=True, on_delete=models.PROTECT)
    id_company = models.ForeignKey(Person, blank=True, null=True, unique=True, on_delete=models.PROTECT)

   class Meta:
       unique_togther = ('id_address', 'id_person', 'id_company')
       # Not sure if it will throw a error here because `id_person` and `id_company` can be blank 
       # or null. But the use of `unique together` is for cases where you want to guarantee 
       # the combination of the primary keys will be unique.

希望有帮助。

关于python - Django OneToOneField 允许在线引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943627/

相关文章:

python / Pandas : Convert multiple CSV files to have union and ordered header and fill the missing data

python - python 中的嵌套索引

php - 检测模型的变化; php yii 框架

javascript - 如何将 json 加载到我的 angular.js ng-model 中?

python - 无法获取 sys.argv[1] 值

Python pandas 如何在将键一直向下存储的同时进行分组

python - 带有 {% trans %} block 的国际化

python - 将表数据 move 并复制到另一个表数据

javascript - 在 django 1.7 中包含静态 js 文件

django - 从不同模型字段名称获取一组对象