【问题标题】:Django - having more than one foreignkey in the same modelDjango - 在同一模型中有多个外键
【发布时间】:2017-10-15 10:42:13
【问题描述】:

models.py

class City(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=35)
    countrycode = models.CharField(max_length=3)
    district = models.CharField(max_length=200)
    population = models.IntegerField(default='0')

class Country(models.Model):
    code = models.CharField(primary_key=True, max_length=3)
    name = models.CharField(max_length=52)
    continent = models.CharField(max_length=50)
    region = models.CharField(max_length=26)
    surfacearea = models.FloatField()
    indepyear = models.SmallIntegerField(blank=True, null=True)
    population = models.IntegerField()
    lifeexpectancy = models.FloatField(blank=True, null=True)
    gnp = models.FloatField(blank=True, null=True)
    gnpold = models.FloatField(blank=True, null=True)
    localname = models.CharField(max_length=45)
    governmentform = models.CharField(max_length=45)
    headofstate = models.CharField(max_length=60, blank=True, null=True)
    capital = models.IntegerField(blank=True, null=True)
    code2 = models.CharField(max_length=2)

模型的 SQL

对于城市 INSERT INTO city VALUES (3955,'Sunnyvale','USA','California',131760);

国家/地区 INSERT INTO country VALUES ('BHS','Bahamas','North America','Caribbean',13878.00,1973,307000,71.1,3527.00,3347.00,'The Bahamas','Constitutional Monarchy','Elisabeth II',148,'BS');

问题 1 在上述模型中,我如何将Country.code 中的代码与City.countrycode 关联起来,我无法这样做,因为 Country 模型是在 City 模型之后声明的。

问题 2 以及如何将 Country.capital in 与 Country 模型联系起来,该模型是与 City.name 相关的整数。

注意 我正在使用 InnoDB 引擎将 .sql 文件转换为 Postgresql。

【问题讨论】:

    标签: python mysql django postgresql pgadmin


    【解决方案1】:

    看来你需要通过字符串声明foreign key

    class City(models.Model):
        name = models.CharField(max_length=35)
        countrycode = models.ForeignKey('Country', blank=True, null=True)
    
    
    class Country(models.Model):
        code = models.CharField(primary_key=True, max_length=3)
        name = models.CharField(max_length=52)
        capital = models.ForeignKey('Country', blank=True, null=True)
    

    【讨论】:

    • 我不明白,我得到 city.countrycode_id 不存在 错误
    • 是的,我不明白id 列是如何自动添加到表格中的。
    猜你喜欢
    • 2017-06-01
    • 2020-12-23
    • 2010-10-07
    • 2015-03-28
    • 2019-03-18
    • 2011-11-15
    • 2021-10-31
    • 2020-05-07
    相关资源
    最近更新 更多