繁体   English   中英

选择共享多对多关系的对象(Django)

[英]Select objects that share a ManyToMany Relationship (Django)

我有一个名为House的模型,另一个名为Location的模型,彼此之间具有ManyToMany关系。 例如,房屋既可以位于Brooklyn ,也可以New York

在我的New York页面上,我想显示“相关位置”或“附近位置”。 我想选择所有与New York共享同一房屋的位置。

例如。

房子: BrooklynNew York

众议院B: ManhattanNew York

我想从New York选择在Manhattan Brooklyn地点。

我也想按他们共有的房屋数量来订购它们。 首先获取最“相关”的位置。

有任何想法吗?

这是一些(未经测试的)代码,应该为您提供如何实现此目标的线索:

# my_location is a Location object representing New York
similar_locations = {}

for house in House.ojects.filter(locations=my_location):  # get all houses in New York
    for house_location in house.locations.all():  # get all locations of all houses in New York
        # count the houses in each location
        if not house_location.pk in similar_locations:
            similar_locations[house_location.pk] = 1 
        else:
            similar_locations[house_locoation.pk] += 1

# sort the dictionary of locations by number of houses
# sorted_similar_locations will be a list of tuples sorted by the second element in each tuple.
import operator
sorted_similar_locations = reversed(sorted(similar_locations.items(), key=operator.itemgetter(1)))

# get Django objects of your locations (this depends on how many similar locations you expect. If it is a lot, this query is very inefficient)
locations = Location.objects.filter(pk__in=similar_locations.keys())

可能有更有效的方法可以做到这一点。 但这应该给您一个好的开始! 希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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