I have a model called House
and another one called Location
which have a ManyToMany relationship between eachother. Example, a house can be in both location Brooklyn
and in New York
.
From my New York
page, I want to display "Relevant Locations" or "Nearby Location". I want to select all locations that share the same houses as New York
do.
So for example.
House A: Brooklyn
, New York
House B: Manhattan
, New York
From New York
I want to select locations Brooklyn
, Manhattan
.
I would also like to order them by the amount of houses they share. To get the most "relevant" location first.
Any ideas?
Here is some (untested) code that should give you a clue on how you can achieve this:
# 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())
There are probably more efficient ways on doing this. But it should give you a good start! Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.