Reputation: 497
I'm using MySQL, and I have two models:
class District(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class School(models.Model):
name = models.CharField(max_length=100)
school_id = models.IntegerField(default=0)
district = models.ForeignKey(District)
When I try to query my School model:
schools = School.objects.filter(district = 'Norfolk')
It tells me I need to use an int() - which leads me to believe it wants the primary key id of the district, not the name of the district. In my admin, the school's district is the string "Norfolk", but in Sequel Pro - it lists district_id, and references the id of the district.
Did I set up my models wrong? Why can't I just pass the name of the district to the School model?
Upvotes: 1
Views: 80
Reputation: 3813
If you want to filter by name, you should use
schools = School.objects.filter(district__name = 'Norfolk')
You should notice that there might be more than one disctrict with that name, as it is not a key of the model District
(i.e. it isn't unique for it).
Upvotes: 1
Reputation: 16197
Have a look at the Django docs. You should use the ForeignKey.to_field
. By default the primary key for the related model is used. In this case it would be district_id
and you'd want it to be name
.
Upvotes: 0