2017-10-15 4 views
0

models.pyDjango - mehr als ein foreignkey im selben Modell mit

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 Für die Modelle

für City INSERT INTO city VALUES (3955,'Sunnyvale','USA','California',131760);

für Land 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');

Frage 1 In den oben genannten Modellen, wie ich Code in den Country.code-City.countrycode beziehen kann, bin ich nicht in der Lage, dies zu tun, weil Land Modell nach dem Stadtmodell erklärt.

Frage 2 Und wie die Country.capital in das Land Modell zu verbinden, die eine ganze Zahl ist, die City.name bezieht.

Hinweis Ich bin eine .sql Datei mit InnoDB-Engine Postgresql konvertieren.

Antwort

0

sieht aus wie Sie foreign key durch Zeichenfolge im Zusammenhang müssen erklären

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) 
+0

Ich verstehe nicht, ich erhalte * city.countrycode_id existiert nicht * Fehler –

+0

hast du getan Migrationen? –

+0

Ja, ich verstehe nicht, wie die ID-Spalte automatisch zur Tabelle hinzugefügt wird. –

Verwandte Themen