3

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
mogoh
  • 992
  • 2
  • 7
  • 27
  • 1
    Have you tried appending `.distinct()`? [See the docs.](https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.distinct) – Paulo Scardine May 22 '17 at 13:53
  • Yes. It does not help. :( – mogoh May 22 '17 at 14:00
  • "there could potentially be multiple ordering data for each Event; each Event with multiple children will be returned multiple times into the new QuerySet that order_by() creates. In other words, using order_by() on the QuerySet could return more items than you were working on to begin with - which is probably neither expected nor useful." - From the docs for [`order_by`](https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.order_by) – Sayse May 22 '17 at 14:19
  • I kind of understand the problem but not the solution. – mogoh May 22 '17 at 14:43

1 Answers1

3

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.

Jota
  • 697
  • 10
  • 24
  • 1
    Works fine, thank you. One note: the above line should get executed per request, not just on class-level when the code gets imported. – guettli Aug 09 '22 at 12:31