ivelum / djangoql

Advanced search language for Django
MIT License
1k stars 88 forks source link

Duplicate results in reverse ForeignKey lookup #80

Closed sainak closed 3 years ago

sainak commented 3 years ago

My model structure:

class Car(models.Model):
    name = models.CharField(max_length=50)

class Tyre(models.Model):
    name = models.CharField(max_length=50)
    car = models.ForeignKey(Car, related_name="tyres")

objects:

car = Car(name="car 1")
tyre1 = Tyre(name="tyre 1", car=car)
tyre2 = Tyre(name="tyre 2", car=car)
tyre3 = Tyre(name="tyre 3", car=car)
tyre4 = Tyre(name="tyre 4", car=car)

So when I lookup for tyres.name ~ "tyre" in the CarAdmin I get 4 results of the same car. I wanted to know if it is possible to filter out duplicate results on admin.

stebunovd commented 3 years ago

Hey @sainAk, what you probably want here is the .distinct() clause. DjangoQL doesn't add it for you because it cannot decide automatically whether its needed. However, you can add it yourself to the resulting queryset produced by DjangoQL. For example, if you're using Django admin integration:

@admin.register(Car)
class CarAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
    def get_search_results(self, request, queryset, search_term):
        qs, use_distinct = super().get_search_results(
            request,
            queryset,
            search_term,
        )
        return qs, True  # always return use_distinct=True
sainak commented 3 years ago

Thanks @stebunovd it works, but passing self in super().get_search_results() will throw a type error so just use *args or remove the self keyword.

stebunovd commented 3 years ago

yep - my bad, I didn't test it. I edited the comment above to fix that