简体   繁体   中英

Does foreign key have to be primary key in Django?

Can we use any other unique column as foreign key in django model?

Yes you can. Column must be unique=True.

To reference this column, specify to_fied attribute on source column. Check below;

class Group (models.Model):
    name= models.CharField(max_length=250)
    otherid=models.IntegerField(unique=True)

class Member (models.Model):
    name=models.CharField(max_length=250)
    group=models.ForeignKey(Group,models.CASCADE,to_field='otherid')

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