我是 Django 框架的新手,我正在尝试构建以下系统,其中包含一个关注多个股票的用户,并且这些股票被多个人关注,我正在尝试使用中间类创建一个复合键,但是我遇到了这个错误。
class Stock(models.Model):
symbol = models.CharField(max_length=12, primary_key=True,default="")
name = models.CharField(max_length=64)
top_rank = models.IntegerField(null=True)
price = models.FloatField()
change = models.FloatField(null=True)
change_percent = models.FloatField()
market_cap = models.FloatField(null=True)
primary_exchange = models.CharField(null=True, max_length=32) # NASDAQ
followers = models.ManyToManyField('myapp.Users',through='Follow',through_fields=('u_id','s_id'))
class Users(models.Model):
user_id = models.IntegerField(primary_key=True,default="")
name = models.CharField(max_length=12)
class Follow(models.Model):
u_id=models.ForeignKey('Users',on_delete=models.CASCADE)
s_id=models.ForeignKey('Stock',on_delete=models.CASCADE)
myapp.Stock.followers: (fields.E339) 'Follow.s_id' is not a foreign key to 'Users'.
HINT: Did you mean one of the following foreign keys to 'Users': u_id?
myapp.Stock.followers: (fields.E339) 'Follow.u_id' is not a foreign key to 'Stock'.
HINT: Did you mean one of the following foreign keys to 'Stock': s_id?
最佳答案
through_fields
[Django-doc] 的顺序是不正确的。正如文档中所指定的:
through_fields
accepts a 2-tuple('field1', 'field2')
, wherefield1
is the name of the foreign key to the model theManyToManyField
is defined on (...), andfield2
the name of the foreign key to the target model (...).
因此,这意味着 through_fields
的第一项应该是 's_id'
,因为它引用的是 Stock
模型,即模型您在其中定义了 ManyToManyField
,第二项应为 'u_id'
:
class Stock(models.Model):
# …
followers = models.ManyToManyField(
'myapp.Users',
through='Follow',
through_fields=(<b>'s_id','u_id'</b>)
)
话虽这么说,您不需要在这里定义 through_fields
,因为您的 Follow
模型恰好包含两个 ForeignKey
指向不同的模型。事实上,您也不需要定义 through=...
模型,因为它不包含任何额外的字段。
请注意,通常 ForeignKey
不包含 _id
后缀,因为 Django 会自动添加一个带有 _id 的额外字段
后缀,包含引用值的主键。
因此,将模型定义为:
class Stock(models.Model):
symbol = models.CharField(max_length=12, primary_key=True)
name = models.CharField(max_length=64)
top_rank = models.IntegerField(null=True)
price = models.FloatField()
change = models.FloatField(null=True)
change_percent = models.FloatField()
market_cap = models.FloatField(null=True)
primary_exchange = models.CharField(null=True, max_length=32) # NASDAQ
followers = <b>models.ManyToManyField('myapp.User')</b>
class <b>User</b>(models.Model):
user_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=12)
请注意,模型通常具有单数名称,即User
,而不是。Users
关于django-models - 如何修复 '' Follow.s_id' 不是 'Users' 的外键。”在此模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566288/