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

2024-04-26 05:00:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个叫做House的模型和另一个叫做Location的模型,它们之间有很多关系。例如,房子可以位于Brooklyn位置和New York位置。你知道吗

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

举个例子。你知道吗

房子A:BrooklynNew York

B栋:ManhattanNew York

New York我想选择位置BrooklynManhattan。你知道吗

我还想按他们合租的房子数量订购。首先得到最“相关”的位置。你知道吗

有什么想法吗?你知道吗


Tags: 模型new数量关系location页面例子house
1条回答
网友
1楼 · 发布于 2024-04-26 05:00:38

以下是一些(未经测试的)代码,可以为您提供如何实现这一点的线索:

# 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())

也许有更有效的方法可以做到这一点。但它应该给你一个好的开始!希望这有帮助。你知道吗

相关问题 更多 >