當您創建從一個模型到另一個模型的關係時,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。