NickP
NickP

Reputation: 1414

Filter objects that exist in the Foreign Key relationship

I have the following relationship in my data:

Models:

class Course(models.Model):
    name = models.CharField(max_length=200)
    concepts = models.ManyToManyField(Concept, related_name='course_concepts')

class Concept(models.Model):
    name = models.CharField(max_length=120)

But I would like to build a query set of Concepts that belong to a particular course (course_x).

I have tried the following but continuously get reference errors:

Concept.objects.filter(self__in=course_x)

As such, what is the correct way to query only objects that match a foreign key relationship for a particular object?

Upvotes: 0

Views: 281

Answers (1)

YPCrumble
YPCrumble

Reputation: 28662

Here is how you might filter for Concept objects that pertain to a Course with a particular name:

concepts = Concept.objects.filter(course__name="Your course name")

Or, you could filter for concepts that relate to a queryset of courses:

concepts = Concept.objects.filter(course__name__icontains="mathematics")

Upvotes: 1

Related Questions