我有三个相互关联的模型:
地址/models.py:
class Town(models.Model):
name = models.CharField(max_length=200, db_index=True, unique=True)
def __str__(self):
return '%s' % self.name
def get_absolute_url(self):
return reverse('home:home_by_town', args=[self.slug])
class Street(models.Model):
town = models.ForeignKey(Town, default=id(1), related_name='streets')
name = models.CharField(max_length=200, db_index=True)
def get_absolute_url(self):
return reverse('home:home_by_town', args=[self.slug])
提供者/models.py:
class Provider(models.Model):
location = models.ManyToManyField(Street, db_index=True, symmetrical=False, related_name='providers')
name = models.CharField(max_length=200, db_index=True)
我已经搜索了为街道服务的提供商:
def search_results(request, town_slug=None):
regions = Region.objects.filter(is_active=True)
town = None
towns = Town.objects.filter(is_active=True)
streets = Street.objects.all()
if town_slug:
town = get_object_or_404(Town, slug=town_slug)
streets = Street.objects.filter(town=town)
streets_list = list(str(p.name) for p in streets)
form = SearchForm()
query = None
results = []
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
results = Provider.objects.prefetch_related('location').annotate(
similarity=TrigramSimilarity('location__name', query), min=Min('tariffs__price'),
).filter(similarity__gt=0.87).distinct().order_by('-similarity')
# tariffs__tariff_details__price
return render(request, 'home/search_results.html', locals())
else:
form = SearchForm()
return render(request, 'home/search_results.html', locals())
这一切都很好,因为我们正在寻找所有街道location__name 记录中的对象,我会对结果感到满意,但我不明白如何将过滤后的街道列表按城市放入 TrigramSimilarity 方法street = Street.objects。过滤器(城镇 = 城镇)
我希望我的搜索结果在这个表现中起作用:
results = Provider.objects.prefetch_related('location').annotate(
similarity=TrigramSimilarity(streets, query), min=Min('tariffs__price'),
).filter(similarity__gt=0.87).distinct().order_by('-similarity')
但是这种构造给了我一个异常值:子查询应该只返回一列
有人知道如何解决这个问题吗?也许有人遇到过这个?