以下是我的模特:
class Location(models.Model):
city = models.CharField()
class Competition(models.Model):
name = models.CharField()
location = models.ForeignKey(Location)
class Laureate(models.Model):
name = models.CharField()
competitions = models.ManyToManyField(Competition, through='LaureateCompetition')
class LaureateCompetition(models.Model):
laureate = models.ForeignKey(Laureate)
competition = models.ForeignKey(Competition)
我正在使用PostgreSQL。
我正在尝试根据Laureates
对<{1}}进行分组:
Location
我最终做的是这样的:
[
{
"city": "Moscow",
"laureates" : ["Bob", "Peter", "Maria"]
},
{
"city": "London",
"laureates" : ["Nicolai", "John", "Adam"]
}
]
如果我使用SQL:
locations = []
all_laureate_competitions = LaureateCompetition.objects.select_related().all()
all_competitions = Competition.objects.order_by('location')\
.distinct('location')\
.select_related()
for competition in list(all_competitions):
location = competition.location
competitions = list(set(
[x for x in all_laureate_competitions
if x.competition.location == location]
))
laureates = list(set([x.name for x in competitions]))
locations.append(create_location(location, laureates))
return locations
我真的不喜欢第一种方法。 进行此类查询的常见实践是什么?我应该用原始sql做吗?还有更多的方式吗?
答案 0 :(得分:0)
你可以这样做:
results = []
for location in Location.objects.all():
for competition in location.competition_set.all():
for laurete_competition in competition.laurete_competition_set.all():
results.append(laurete_competition.laurete_set.all())
print results
另见优秀的Django文档,当我遇到类似的问题时,我总是去那里:
https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships