4

I'm curious whether a RelatedField can be used to cause custom join queries. I would like to apply this in django-parler, a multilingual app for Django.

For example, when "slug" is a translated field, I would like to have:

    MyModel.objects.filter(slug="foo")

to operate as:

    MyModel.objects.fiter(translations__slug="foo")

under the hood. This is possible with the API of the RelatedField class for example?

I noticed there are several API hooks in the RelatedField class, such as m2m_reverse_field_name(), m2m_target_field_name(), m2m_column_name(), extra_filters() etc.. which are used in the GenericRelation and django-taggit's TaggableManager classes but I have no idea how these work.

N.B. Field access on instances is covered in django-parler, and I would love to extend that to ORM queries as well.

vdboor
  • 21,914
  • 12
  • 83
  • 96
  • If you modify "filter" this way, you can not combine it with conditions for specify translation language/languages. You can replace the manager (accessible by the name "objects") and add "your_filter" to it. I think it is more robust and your first experiments should be with an added new filter, not comletely replaced. Why you need it? For admin or any app? (I dived into ORM internals when I extened a db driver for a database that doesn't use normal SQL.) – hynekcer Sep 28 '13 at 22:08
  • I don't intend to modify the `filter()` method. Rather, provide the correct results in the `RelatedField` methods, so `.filter()` behaves that way. – vdboor Oct 01 '13 at 10:15

1 Answers1

1

The docs say you can do this to filter by specific translated field:

MyObject.objects.filter(
    translations__language_code__in=get_active_language_choices(),
    translations__slug='omelette'
)

This should fulfill your need to query against the translated "slug" field value in a specific language.

tutuDajuju
  • 10,307
  • 6
  • 65
  • 88
  • Yes, that's what I currenly use. However, I would like to provide an API to the users of my library, so they don't have to. That requires looking into ORM internals (like django-taggit also does for example), but I can't find any documentation on that – vdboor Oct 29 '13 at 10:03
  • Use [custom managers](https://docs.djangoproject.com/en/dev/topics/db/managers/#creating-manager-with-queryset-methods). You can subclass the custom manager used in django-parler – tutuDajuju Oct 29 '13 at 10:25