Django - filtering foreign key properties

I am trying to filter a table in Django based on the value of a specific ForeignKey field.

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 would like to filter my list of assets based on the name of the respective project.

I am currently doing 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 am wondering if there is a way to specify this kind of filtering in the main request?

+73
django django-models django-queryset
Dec 30 '09 at 17:59
source share
3 answers

Asset.objects.filter( project__name__contains="Foo" )

+113
Dec 30 '09 at 18:07
source share

This has been possible since the queryset-refactor branch landed before version 1.0. Ticket 4088 revealed 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 using foreign keys using the model API.

+13
Dec 30 '09 at 18:07
source share
 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 statement above, I assume that after the student is enrolled, an instance of SubjectGrade of the subject will be created, which contains the registered subject and the student himself.

The Subject and Student User models are the foreign key to the SubjectGrade model.

In "available_subjects", I excluded all subjects that are already registered with the current student_user by checking all instances of subjectgrade that have the attribute "student" as the current student_user

PS. I apologize in advance if you still cannot understand because of my explanation. This is the best explanation I can provide. thank you very much

0
Sep 28 '18 at 8:50
source share



All Articles