2013-04-27 87 views
1

我有關係型數據庫和關係的一個看起來像這個類的一個外鍵:Django的:分配還沒有被創建

Student < --- > Major_enrollments 

所以我需要一個外鍵創建列到兩個表中的第二個表。考慮到這個事實,我該怎麼做?如果我定義了這個類,例如學生第一,我會收到這樣的錯誤通知:「NameError:名稱'Major_enrollments'未定義」。

這是一段代碼,我寫的(models.py):

class Students(models.Model): 

    nr_album = models.IntegerField() 
    fName = models.CharField(max_length=70) 
    lName = models.CharField(max_length=70) 
    pesel = models.BigIntegerField() 
    address = models.CharField(max_length=100) 
    major_enrollments = models.ForeignKey(Major_enrollments) #<---THAT DOESN'T WORK 

    def __unicode__(self): 
     return unicode(self.pesel) 


    class Meta: 
     db_table='Students' 

class Major_enrollments(models.Model): 
    majors = models.ForeignKey(Majors) 
    students = models.ForeignKey(Students) 

    def __unicode__(self): 
     return unicode(self.id) 

    class Meta: 
     db_table='Major_enrollments' 

回答

6

可以使用類名(字符串形式),而不是類本身:

class Students(models.Model): 

    nr_album = models.IntegerField() 
    fName = models.CharField(max_length=70) 
    lName = models.CharField(max_length=70) 
    pesel = models.BigIntegerField() 
    address = models.CharField(max_length=100) 
    major_enrollments = models.ForeignKey('Major_enrollments') 

    def __unicode__(self): 
     return unicode(self.pesel) 


    class Meta: 
     db_table='Students' 
+1

+1,你也可以使用'' .Major_enrollments''從外部模塊 – 2013-04-27 12:22:44

+0

哇我沒有經歷ct一個反應如此之快,很好:))..它的工作,但我需要在兩個表中也廣告'相關的名稱',所以它看起來像這樣: major_enrollments = models.ForeignKey('Major_enrollments',related_name ='Students_major_enrollments ') Thanks:)))!!!! – zawit 2013-04-27 12:47:59