模型.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,'桑尼维尔','美国','加利福尼亚',131760);
针对国家/地区
插入国家/地区值('BHS'、'巴哈马'、'北美'、'加勒比'、13878.00、1973、307000、71.1、3527.00、3347.00、'巴哈马'、'君主立宪制'、'伊丽莎白二世',148,'BS');
问题 1
在上述模型中,我如何将 Country.code
中的代码关联到 City.countrycode
,我无法这样做,因为 Country 模型是在 City 模型之后声明的.
问题 2
以及如何链接 Country 模型中的 Country.capital
,它是与 City.name
相关的整数。
注意
我正在使用 InnoDB 引擎将 .sql
文件转换为 Postgresql。
最佳答案
看起来你需要声明 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)
关于python - Django - 在同一模型中有多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754153/