以多对多关系定义默认密钥

时间:2015-10-27 07:50:51

标签: django many-to-many

我以这种方式继承AbstractUser:

class MyUser(AbstractUser):
    customer = models.ManyToManyField(Customer)
    default_customer = models.ForeignKey(Customer)

一个用户可以拥有不同的客户帐户,当然,客户帐户将拥有大量用户。

但我想添加一个将在用户界面中更改的“default_customer”字段。

做到这一点,我收到了一个错误:

profiles.MyUser.customer: (fields.E304) Reverse accessor for 'MyUser.customer' clashes with reverse accessor for 'MyUser.default_customer'.
    HINT: Add or change a related_name argument to the definition for 'MyUser.customer' or 'MyUser.default_customer'.
profiles.MyUser.default_customer: (fields.E304) Reverse accessor for 'MyUser.default_customer' clashes with reverse accessor for 'MyUser.customer'.
    HINT: Add or change a related_name argument to the definition for 'MyUser.default_customer' or 'MyUser.customer'.

我可以在ManyToMany和ForeignKey字段中添加一个related_name,但我的设计是否正常?

1 个答案:

答案 0 :(得分:0)

问题是从Customer导航到MyUser的相关名称,django会自动生成一个在两个关系中发生冲突的名称。要修复它,请指定一个:

class MyUser(AbstractUser):
    customer = models.ManyToManyField(Customer, related_name='users')
    default_customer = models.ForeignKey(Customer, related_name='default_users')