the following structure is given:
class MovieTranslation:
lang=CharField()
title=CharField()
class Movie:
key = CharField()
movie_translations = ManyToManyField(MovieTranslation)
Now for example, for english users I want to sort by the english MovieTranslation
of a Movie
?
I want to use it in a ViewSet
as a Filterset
class.
I think it should be something like order_by(movie_translations__name='en'__title)
. The last part of course doesn't work. I found solutions, for filtering before, but I do not think filtering for english Translations work, since then I get a list of Movie Objects who have an english Title, but could still have other languages. I want to sort specifically by the field of a manytomany field.
So is there a way to order by a specific ManyToMany
Instance (i.e. all MovieTranslations
where the name is 'en' ) ?
I was thinking about annotate, but had the same problems
I am thinking now that maybe joining with a specific ManyToMany
field could work.
CodePudding user response:
Following should work:
Movie.objects
.filter(movie_translations__title='en')
.order_by('movie_translations__title')
Please note that it assumes that all movies have english translation. The SQL query produced by ORM uses INNER JOIN
which will filter out movies that have no translation with title=en
.
CodePudding user response:
Try this
Movie.MovieTranslation.filter(lang="en").order_by("-title")