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[0].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.