I have addresses/models.py:
class Street(models.Model):
...
town = models.ForeignKey(Town, default=None, related_name='streets', on_delete=models.CASCADE, verbose_name='')
name = models.CharField(max_length=200, db_index=True, verbose_name='',
help_text='')
slug = models.SlugField(max_length=200, db_index=True, verbose_name='')
is_active = models.BooleanField(default=True, verbose_name='')
...
And providers/models.py:
class Provider(models.Model):
...
location = models.ManyToManyField(Street, db_index=True, symmetrical=False, related_name='providers',
verbose_name='')
name = models.CharField(max_length=200, db_index=True, verbose_name='')
slug = models.SlugField(max_length=200, db_index=True, verbose_name='')
is_active = models.BooleanField(default=True, verbose_name='')
...
And home/views.py:
def home(request):
...
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.annotate(
similarity=TrigramSimilarity('location__name', query),
).filter(similarity__gt=0.35).order_by('-similarity')
context = {
'form': form,
'query': query,
'results': results,
}
return render(request, 'home/home.html', context)
else:
return render(request, 'home/search_error.html')
context = {
'form': form,
'query': query,
'results': results,
}
return render(request, 'home/home.html', context)
At the front home/home.html:
<!-- provider items in results -->
{% for p in results %}
|it's just here html|
{% endfor %}
As a result (I enter the street name and it finds the correct answer for me, but only lists it as many times as it is mentioned in the request):
I want to make it like this:
question from:
https://stackoverflow.com/questions/65844377/how-to-organize-a-trigram-search-so-that-by-searching-for-a-relation-many-to-man