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对于模型
for City
INSERT INTO city VALUES (3955,'Sunnyvale','USA','California',131760);
for Country
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
国家模型,该模型是与City.name
相关的整数。
注意
我正在使用InnoDB Engine将.sql
文件转换为Postgresql。
答案 0 :(得分:0)
看起来你需要声明与字符串相关的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)