【问题标题】:Can two models reference each other by ForeignKey?两个模型可以通过 ForeignKey 相互引用吗?
【发布时间】:2022-06-29 00:26:52
【问题描述】:

我有两个模型

class Customer(models.Model):
    name = models.CharField(max_length=255, unique=True)
    default_contact = models.ForeignKey("CustomerContact", verbose_name="...", related_name="default_contacts", null=True, on_delete=models.SET_NULL)
    etc.

class CustomerContact(models.Model):
    customer = models.ForeignKey(Customer, related_name='contacts')
    user = models.OneToOneField(User, related_name='user_contacts', on_delete=models.SET_NULL)
    address = models.ForeignKey(CustomerAddress, ....)

在本例中,Customer 指向 CustomerContact。 同时CustomerContact指向Customer

我的同事说,将 Customer 指向 CustomerContact 违反了 ForeignKey 的 OneToMany 特性。 我做错了什么?

【问题讨论】:

    标签: django django-models foreign-keys


    【解决方案1】:

    正如我所见,您希望多个CustomerContact 与一个Customer 相关,但Customer 也可以选择他最喜欢的(或者可以由经理设置)。这是有效的方法。

    只要您能妥善保护related_names,它就可以双向使用。

    default_contact = models.ForeignKey("CustomerContact", ... related_name="default_contacts") <= should be changed
    

    default_contacts 应更改(即更改为 default_for_customers),因为此名称用于反向关系,因此实际上用于 CustomerContact。这意味着,您可以在以下情况下使用它:

    cc = CustomerContact.objects.get(id=1)
    cc.default_for_customers.all()  <= this will return QuerySet of Customer objects that is default for
    

    它更简单,更不容易混淆。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      相关资源
      最近更新 更多