I have a broker model and a city model with the Broker model defined like this:
class Broker(models.Model):
user = models.ForeignKey(Auth)
areas_of_operation = models.ManyToManyField(City)
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)
state = models.ForeignKey(State, unique=True)
zip = models.IntegerField(max_length=5)
Of course this will yield an error but I was wondering if there was any way I can facilitate a relationship that indicates that a Broker can work in many cities but lives in only one city. Or is this a high level design issue in which I must create more tables to show that relationship?
When you create a relationship from one model to the other, Django automatically adds a reverse relationship in the other direction. For example, if you got rid of the
areas_of_operationfield temporarily, it would work and you could use the codecity.broker_set()to get all the brokers who live in a given city.However, when you create multiple links from one model to another, Django tries to create multiple reverse relationships under the same attribute name. This is borne out by the error message when you run
manage.py validateon your models:In other words, the problem is not in having multiple links from
BrokertoCity, but rather the automatic reverse relationship having the same default name for both links. To get around this, use therelated_nameargument to set the name to use for the reverse relationship. The following code worked for me:Now, if you have a
Cityobject, you can callcity.operators()to get a list of who operates in that city, andcity.citizens()for a list of who lives there.See the Django model field documentation for further information on relationship fields.