[英]Select objects that share a ManyToMany Relationship (Django)
我有一個名為House
的模型,另一個名為Location
的模型,彼此之間具有ManyToMany關系。 例如,房屋既可以位於Brooklyn
,也可以New York
。
在我的New York
頁面上,我想顯示“相關位置”或“附近位置”。 我想選擇所有與New York
共享同一房屋的位置。
例如。
房子: Brooklyn
, New York
眾議院B: Manhattan
, New 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.