简体   繁体   中英

Query Django models two levels down foreign key relations

I am building a dictionary application using Django. The main models in this app are Expression s, Definition s, and City s. The logic is that each Expression has one or more Definition s, and each Definition is associated with one City .

Here is my problem : I want to query all the City s associated with an Expression , from the Expression level.

For example, I would like to do an_expression.cities and get all the City s associated with (each Definition of) an_expression .

Here are my models :

class City(models.Model):
    city = models.CharField()

class Expression(models.Model):
    expression = models.CharField()
    cities = models.ManyToManyField(City, related_name="expressions")

class Definition(models.Model):
    city = models.ForeignKey(City, related_name="definitions")
    expression = models.ForeignKey(Expression, related_name="definitions")

This code now works. However, every time I add a Definition I need to add the City to both the Expression --AND-- the Definition itself.

Here is my question : Is there a way to only add the City to the Definition , and then somehow be able to query an_expression.cities and get all cities (basically getting rid of the cities field in the Expression model)?

Do not use identical related_name for different foreign keys in Definition class

class Definition(models.Model):
    city = models.ForeignKey(City, related_name="definitions_city")
    expression = models.ForeignKey(Expression, related_name="definitions_expression")

You can get city list for Expression like this

an_expression = Expression.objects.first()
an_expression.definitions_expression.values('city__city')

So no need for cities ManyToManyField in Expression class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM