我有球员,球队和比赛的模型。显然,我有一些ForeignKey字段。但是,如果我未在ForeignKey字段的末尾添加“ _id”,则Django会引发错误:“无此类列:betbot_testmatch.leftTeam_id”
我试图在我的ForeignKey字段的末尾添加“ _id”,这确实解决了问题,但是在我设计的上一个项目中,我一直使用FK字段,而在字段名的末尾没有任何“ _id”没问题。
models.py
from django.db import models
class TestMatch(models.Model):
leftTeam = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, related_name='+', default='Left Team')
rightTeam = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, related_name='+', default='Right Team')
class TestTeam(models.Model):
name = models.CharField(max_length=30, default='Team')
urlslug = models.SlugField(max_length=5)
class TestPlayer(models.Model):
name = models.CharField(max_length=100, default='Player')
nick = models.CharField(max_length=20, default='Nickname')
team_id = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, default='Team')
#photo = models.ImageField(upload_to='', null=True)
No = 'N'
Yes = 'Y'
STANDIN_CHOICES = [
(Yes, 'Yes'),
(No, 'No'),
]
standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No)
slug = models.SlugField(max_length=20, default=nick)
我希望我的名字可以用于ForeignKey字段而不会出错。
答案 0 :(得分:0)
在模型上有一个ForeignKey
字段时,Django会在后台进行一些操作
class Foo(models.Model):
bar = models.ForeignKey(Bar, on_delete=models.CACSCADE)
Foo
的每个实例现在都有两个属性
foo = Foo()
# This is a descriptor that will perform a DB lookup for the
# related model and return it or raise an exception
foo.bar
# This will return the actual value stored in the database
# that is used by the descriptor to lookup the related model
# by default this will be the id
foor.bar_id
答案 1 :(得分:0)
问题已解决。事实是,在TestMatch中,除了ForeignKey之外没有任何其他字段,因此Django无法为其创建ID。