简体   繁体   English

外键是否必须是 Django 中的主键?

[英]Does foreign key have to be primary key in Django?

Can we use any other unique column as foreign key in django model?我们可以在 django model 中使用任何其他唯一列作为外键吗?

Yes you can.是的你可以。 Column must be unique=True.列必须是唯一的=True。

To reference this column, specify to_fied attribute on source column.要引用此列,请在源列上指定to_fied属性。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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