我有一个名为House的模型和另一个名为Location的模型,它们彼此之间具有ManyToMany关系。例如,房屋既可以位于location Brooklyn,也可以位于New York。
在我的New York页面上,我想显示“相关位置”或“附近位置”。我想选择与New York共享相同房屋的所有位置。
举个例子。
房屋A:Brooklyn,New York
房屋B:Manhattan,New York
我想从New York中选择位置Brooklyn,Manhattan。
我还想根据他们分享的房屋数量对他们进行排序。首先获取最“相关”的位置。
有什么想法吗?
发布于 2015-03-24 16:27:57
以下是一些(未经测试的)代码,它们将为您提供如何实现此目标的线索:
# 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())可能有更有效的方法来做到这一点。但这应该会给你一个好的开始!希望这能有所帮助。
https://stackoverflow.com/questions/29226811
复制相似问题