【发布时间】:2018-05-27 19:36:46
【问题描述】:
Djangonauts,我需要挖掘你的大脑。
简而言之,我有以下三个模型:
class Location(models.Model):
name = models.CharField(max_length=100)
class Profile(models.Model):
locations_of_interest = models.ManyToManyField(Location)
class Question(models.Model):
locations = models.ManyToManyField(Location)
我想查找感兴趣的位置与为特定问题指定的位置相交的所有配置文件。这很简单:
question = Question.objects.first()
matching_profiles = Profile.objects.filter(
locations_of_interest__in=question.locations.all()
)
但除此之外,我还想知道这些位置重叠到什么程度。
在普通的 python 中,我可以这样做:
question_location_names = [l['name'] for l in question.locations.all()]
for profile in matching_profiles:
profile_location_names = [l['name'] for l in profile.locations_of_interest.all()]
intersection = set(question_location_names).intersection(profile_location_names)
intersection_count = len(list(intersection))
# then proceed with this number
但是,如果可能的话,在我看来直接在数据库中进行操作似乎是有利的。
TL;DR
所以我的问题是:
有没有办法用这个交集计数注释配置文件查询集,然后在数据库中进行操作?
我尝试了几件事,但我认为它们对阅读本文并可能知道答案的人没有帮助。
【问题讨论】:
标签: python django django-models django-queryset