Django ManyToManyField SystemCheckError

时间:2015-10-30 19:38:53

标签: django django-models

class Professional(models.Model):
    ...
    favoriting_customers = models.ManyToManyField(
        'customers.Customer', blank=True,
        through='favorites.FavoriteProfessional')

    recommending_customers = models.ManyToManyField(
        'customers.Customer', blank=True,
        through='recommendations.ProfessionalRecommendation')

当我删除ManyToMany字段时,我没有错误。但是,当我运行' python manage.py makemigrations'时,我得到了SystemCheckError。

错误: professional.Professional.favoriting_customers :( fields.E304)' Professional.favoriting_customers'的反向访问者与“Professional.recommending_customers'”的反向访问者发生冲突。     提示:在' Professional.favoriting_customers'的定义中添加或更改related_name参数。或者' Professional.recommending_customers'。 professional.Professional.recommending_customers :( fields.E304)' Professional.recommending_customers'的反向访问者与“Professional.favoriting_customers'”的反向访问者发生冲突。     提示:在' Professional.recommending_customers'的定义中添加或更改related_name参数。或者' Professional.favoriting_customers'。

1 个答案:

答案 0 :(得分:1)

根据 HINT 的建议,您需要使用related_name来避免backward relations上的冲突。每次在同一模型中有两个与同一对象相关的字段(在您的情况下为customers.Customer)时,您将需要这样做。

您可以尝试这样的事情:

class Professional(models.Model):
    ...
    favoriting_customers = models.ManyToManyField(
        'customers.Customer', blank=True,
        through='favorites.FavoriteProfessional',
        related_name='favorites'
    )

    recommending_customers = models.ManyToManyField(
        'customers.Customer', blank=True,
        through='recommendations.ProfessionalRecommendation',
        related_name='recommendations'
    )

如果您对Professional表的向后关系不感兴趣,可以使用'+'作为related_name禁用它:

class Professional(models.Model):
    ...
    favoriting_customers = models.ManyToManyField(
        'customers.Customer', blank=True,
        through='favorites.FavoriteProfessional',
        related_name='+'
    )

    recommending_customers = models.ManyToManyField(
        'customers.Customer', blank=True,
        through='recommendations.ProfessionalRecommendation',
        related_name='+'
    )

此外,您应该be careful with related_name