Not able to filter() on foreign keys.
|Reported by:||no@…||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Severity:||Keywords:||filter foreignkey, qs-rf-fixed|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||yes||Patch needs improvement:||no|
I'm trying to filter by a value that is contained in a foreign key. I've seen this done in the django documentation (the blog example).
Here are my models:
class Students(models.Model): ssn = models.CharField(unique=True, maxlength=11) name = models.CharField(blank=True, maxlength=50) address = models.CharField(blank=True, maxlength=50) dob = models.DateField(null=True, blank=True) email = models.CharField(blank=True, maxlength=50) level = models.CharField(blank=True, maxlength=5) def __str__(self): return self.ssn class Takes(models.Model): student = models.ForeignKey(Students, to_field='ssn', db_index=True, db_column='ssn') course = models.ForeignKey(Courses, to_field='cid', db_index=True, db_column='cid') semester = models.ForeignKey(Semesters, to_field='sname', db_index=True, db_column='sname') grade = models.CharField(blank=True, maxlength=2) def __str__(self): return "%s - %s" % (self.course.cid, self.semester.sname)
The other models aren't relevant to the question. We are just focusing on the student foreign key inside Takes.
Now, here is an example of me trying to filter by someone's name
>>> Takes.objects.filter(student__name="Kevin Smith")  >>> Takes.objects.get(id=1).student.name 'Kevin Smith' >>>
I've also tried every combination of icontains. To circumvent this, I've been using the code below (if it helps)
takes = Takes.objects.all() takes2 =  for x in takes: if (x.student.name).lower().find("kev".lower()) != -1: takes2.append(x)
And takes2.student.name returns "Kevin Smith".
Maybe I'm missing something totally, which I would love to know. But this feels like a bug to me.
Change History (11)
comment:1 follow-up: ↓ 2 Changed 8 years ago by Gary Wilson <gary.wilson@…>
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
Changed 8 years ago by no@…
comment:6 Changed 8 years ago by no@…
- Has patch set
- Needs tests set
- Version changed from 0.96 to SVN