Duplicate results when querying using SearchVector

Viewed 228

I have an abstract model class called PostType with a few submodels derived from it. The model looks like this:


class PostType(models.Model):
    title = models.CharField(
        max_length=255,
        unique=True,
        verbose_name='Title'
    )
    description = models.CharField(
        max_length=255,
        default='',
        verbose_name='Description'
    )
    tags = models.ManyToManyField(
        to=Tag,
        blank=True,
        verbose_name='Tags'
    )
    content = RichTextUploadingField(
        default='',
        verbose_name='Post Content'
    )

    class Meta:
        abstract = True

It has a related Tag model that looks like this:


class Tag(models.Model):
    name = models.CharField(
        max_length=255,
        verbose_name='Name',
        unique=True
    )
    description = models.TextField(
        verbose_name='Description',
        default=''
    )

In one of my views I am trying to query all of the subclasses, using a SearchVector and searching multiple fields:


query = request.GET.get('s')

from django.contrib.postgres.search import SearchVector
get_qs_list = [model.objects.annotate(
    search=SearchVector('title', 'description', 'content', 'tags__name')
).filter(search=query) for model in models.PostType.__subclasses__()]

Now, the search is returning all of the results that it should. However, for some reason it's returning duplicate results for some items.

The problem seems to go away if I remove 'tags__name' from the SearchVector, but I don't understand why.

What am I doing wrong, and why does it work if I don't search the related field?

EDIT:

I just realized that I get a duplicate result for every Tag that the item is related to. So if the item has three tags, I will get three copies of the item in the search result. I still don't understand why this happens though, and I'm grateful for any advice!

0 Answers
Related