简体   繁体   中英

Confused about ForeignKey model relationship in Django

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?

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 (ie it isn't unique for it).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM