188

I'm trying to filter a table in Django based on the value of a particular field of a ForeignKey.

For example, I have two models:

class Asset(models.Model):
    name = models.TextField(max_length=150)
    project = models.ForeignKey('Project')

class Project(models.Model):
    name = models.TextField(max_length=150)

I'd like to filter my asset list based on the name of the associated project.

Currently, I am performing two queries:

project_list = Project.objects.filter(name__contains="Foo")
asset_list = Asset.objects.filter(desc__contains=filter,
                                  project__in=project_list).order_by('desc')

I'm wondering if there is a way to specify this kind of filtering in the main query?

2
  • 1
    I am confused, is it true that project__in=project_list should be Project__in=project_list (should it case sensitive) since you assign in model Project
    – Chau Loi
    Feb 18, 2021 at 9:00
  • 1
    @ChauLoi, no think of it like just another field of the Model. Jul 26, 2022 at 5:42

3 Answers 3

268
Asset.objects.filter( project__name__contains="Foo" )
3
  • 1
    Thanks, I had tried that but apparently I had forgotten to use double underscore. Dec 30, 2009 at 18:13
  • 4
    is contains necessary?? Jul 11, 2015 at 7:08
  • 2
    @DeadDjangoDjoker contains describes the type of comparison used in the query that the django ORM produces, the sql will probably look like LIKE '%Foo%'. Apr 7, 2020 at 0:43
26

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

3
  • 1
    Is this going to hit the DB twice, should I be using select_related() to make this more optimal? Dec 30, 2009 at 22:52
  • 6
    You can add a .query.as_sql() to see what sql will actually be executed. Jul 17, 2010 at 5:19
  • the link to the django docs is completely out of date and lands on a '410 Page removed' :-/
    – szeitlin
    Oct 9, 2015 at 17:14
0
student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.