Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter django queryset including a specific object in manytomany field

Here is my models,

class Age(models.Model):
    layer = models.CharField(max_length=50)
    order = models.PositiveIntegerField()
    ...
class Course(models.Model):
    target_age = models.ManyToManyField('Age')
    ...

How can I get a course queryset including a specific age?
views:

request_courses = Course.objects.filter(target_age ...
like image 593
koichi_n Avatar asked Dec 01 '22 23:12

koichi_n


1 Answers

Your question is a little vague. First, have a read of the documentation on querying across relationships.

If you want to get courses related to only those Age's with a particular field value:

Course.objects.filter(target_age__FIELD=...)

where FIELD is the field in your Age model you want to query against.

Alternatively, if you have an Age object and you want to get all courses that are actually related to a particular Age object, you need:

age = Age.objects.get(...)
courses = Course.objects.filter(target_age=age)

or if you want to get courses that are related to at least one of a number of possible Age's:

ages = Age.objects.filter(...)
courses = Course.objects.filter(target_age__id__in=ages.values_list('id'))

EDIT

The last example is using the in lookup

like image 74
Timmy O'Mahony Avatar answered Mar 23 '23 23:03

Timmy O'Mahony