当您创建从一个模型到另一个模型的关系时,Django 会自动在另一个方向添加反向关系。例如,如果您暂时去掉 areas_of_operation 字段,它会起作用,您可以使用代码 city.broker_set() 来获取居住在给定城市的所有经纪人。
但是,当您创建从一个模型到另一个模型的多个链接时,Django 会尝试在同一属性名称下创建多个反向关系。当您在模型上运行 manage.py validate 时,错误消息证实了这一点:
Error: One or more models did not validate:
myapp.broker: Accessor for field 'city' clashes with related m2m field 'City.broker_set'. Add a related_name argument to the definition for 'city'.
myapp.broker: Accessor for m2m field 'areas_of_operation' clashes with related field 'City.broker_set'. Add a related_name argument to the definition for 'areas_of_operation'.
换句话说,问题不在于从Broker 到City 的多个链接,而是两个链接具有相同默认名称的自动反向关系。要解决此问题,请使用 related_name 参数设置用于反向关系的名称。以下代码对我有用:
from django.contrib.auth.models import User
from django.db import models
class State(models.Model):
name = models.CharField(max_length=100)
class City(models.Model):
name = models.CharField(max_length=100)
class Broker(models.Model):
user = models.ForeignKey(User)
areas_of_operation = models.ManyToManyField(City, related_name='operators')
phone = models.CharField(max_length=20)
company_name = models.CharField(max_length=50)
address1 = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
city = models.ForeignKey(City, related_name='citizens')
state = models.ForeignKey(State, unique=True)
zip = models.IntegerField(max_length=5)
现在,如果您有 City 对象,您可以致电 city.operators() 获取在该城市运营的人员列表,并致电 city.citizens() 获取居住在那里的人员列表。
有关关系字段的更多信息,请参阅Django model field documentation。