简体   繁体   English

为什么Django在ForeignKey字段名称中要求“ _id”?

[英]Why Django requires “_id” in the name of ForeignKey field?

I have models for players, teams and matches. 我有球员,球队和比赛的模型。 Obviously, that I have some ForeignKey field. 显然,我有一些ForeignKey字段。 But if I don't add "_id" in the end of ForeignKey field, Django raises the error: "no such column: betbot_testmatch.leftTeam_id" 但是,如果我未在ForeignKey字段的末尾添加“ _id”,则Django会引发错误:“无此类列:betbot_testmatch.leftTeam_id”

I have tried to add "_id" in the end of my ForeignKey fields and it really solved the problem, but in my previous project I designed, I have been usin FK fields without any "_id" in the end of field names and there were no problems. 我试图在我的ForeignKey字段的末尾添加“ _id”,这确实解决了问题,但是在我设计的上一个项目中,我一直在FK字段中使用,而在字段名的末尾没有任何“ _id”没问题。

models.py 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)

I want that I could use my names for ForeignKey field without the mistake. 我希望我可以将我的名字用于ForeignKey字段而不会出现错误。

When you have a ForeignKey field on a model, Django does a few things under the hood 当您在模型上有一个ForeignKey字段时,Django会在后台进行一些操作

class Foo(models.Model):
    bar = models.ForeignKey(Bar, on_delete=models.CACSCADE)

Every instance of Foo now has two attributes 现在,每个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

Problem is solved. 问题解决了。 The thing was that in the TestMatch wasn't any fields but ForeignKey, so Django couldn't create id for it. 事实是,在TestMatch中,除了ForeignKey之外没有任何其他字段,因此Django无法为其创建ID。

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

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