如何将已存在的字段设置为另一个 table 的外键?
How to set already existing field as a foreign key to another table?
A 有两个包含数据的模型表。
class A(models.Model):
id = models.PositiveIntegerField(primary_key=True)
#some other fields
other_id = models.IntegerField(default=0, null=True)
第二个class
class B(models.Model):
id = models.PositiveIntegerField(primary_key=True)
#some other fields
现在我希望字段 A.other_id
成为与 field B.id
相关的 ForeignKey
。
我不能使用 SQL。我知道它应该是这样的:
b = models.ForeignKey(B, db_column="other_id")
不过好像不行。
您尝试过 to_field
选项吗?
你可以这样做:
b = models.ForeignKey(B, to_field="other_id")
但是,要注意的是字段 other_id
必须满足 unique=True
.
A 有两个包含数据的模型表。
class A(models.Model):
id = models.PositiveIntegerField(primary_key=True)
#some other fields
other_id = models.IntegerField(default=0, null=True)
第二个class
class B(models.Model):
id = models.PositiveIntegerField(primary_key=True)
#some other fields
现在我希望字段 A.other_id
成为与 field B.id
相关的 ForeignKey
。
我不能使用 SQL。我知道它应该是这样的:
b = models.ForeignKey(B, db_column="other_id")
不过好像不行。
您尝试过 to_field
选项吗?
你可以这样做:
b = models.ForeignKey(B, to_field="other_id")
但是,要注意的是字段 other_id
必须满足 unique=True
.