Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django remove duplicates of a QuerySet when using parler

I have a model like this:

from django.db import models
from django.utils.translation import ugettext_lazy as _

from parler.models import TranslatableModel, TranslatedFields

...

class UnitNode(TranslatableModel):
    ...
    translations = TranslatedFields(
        title=models.CharField(_(u'title'), max_length=1024),
        slug=models.SlugField(_('slug'))
        ),
    )

...

I want a QuerySet of UnitNodes without duplicates, sorted by slug. When I query something like this:

qs = UnitNode.objects.distinct().order_by("translations__slug")

I get duplicates.

How do I get rid of duplicates?

like image 845
mogoh Avatar asked Oct 14 '25 16:10

mogoh


1 Answers

The solution is:

from django.utils.translation import get_language
Country.objects.translated(get_language()).order_by("translations__name")

This way you only get the instances for the current language in use in the app and it won't generate duplicates. Just as you were doing it gets all instances of all languages ​​by duplicating itself in different languages.

like image 168
Jota Avatar answered Oct 17 '25 10:10

Jota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!