8๐
โ
Option 1: use the
Option 2: set a
If you set the related_query_name
[Django-doc], then that is the name you should use when filtering in reverse. If you set the related_name
[Django-doc], and not a related_query_name
, then Django will use the related_name
for the related_query_name
as well. If you do not set a related_name
and related_query_name
, then related_name
will default to modelname_set
(so here category_set
) and related_query_name
to modelname
(so here category
).
Option 1: use the related_name
So you can filter with the related_name
in your query:
CourseRun.objects.filter(course__category_set__in=[1, 2])
Option 2: set a related_query_name
Another option is to set the related_query_name
to something else, for example 'category'
:
class Category(models.Model):
courses = models.ManyToManyField(
Course,
related_name='category_set',
related_query_name='category'
)
Then you can filter with:
CourseRun.objects.filter(course__category__in=[1, 2])
Source:stackexchange.com