2012-11-03 115 views
0

Im新django。我有這個模型,在tblperson中,只保存了類型和狀態的僞造鍵。我如何加入所有表格來顯示他們的價值而不是他們的僞造鑰匙?例如。django加入查詢

TblPerson.objects.raw('SELECT * FROM "Tblperson" INNER JOIN "Tblstatus" ON ("TblPerson"."Status" = "Tblstatus"."ID")'): 

謝謝。

class TblPerson(models.Model): 
    ID = models.AutoField(primary_key=True, db_column=u'ID') 
    Type = models.IntegerField(null=True, db_column=u'Type', blank=True) 
    Status = models.IntegerField(null=True, db_column=u'Status', blank=True) 
    class Meta: 
     db_table = u'tblPerson' 

class Tblstatus(models.Model): 
    ID = models.AutoField(primary_key=True, db_column=u'statStatusID') 
    Status = models.CharField(max_length=25, db_column=u'statStatus', blank=True) 
    class Meta: 
     db_table = u'tblStatus' 

class Tbltype(models.Model): 
    ID = models.AutoField(primary_key=True, db_column=u'typTypeID') 
    Type = models.CharField(max_length=25, db_column=u'typType', blank=True) 
    class Meta: 
     db_table = u'tblType' 

回答

1

的Django的力量是在ORM,這意味着你應該,如果在所有被寫入很少的SQL。

class Person(models.Model): 
     #don't use this because id is generated automatically 
     #ID = models.AutoField(primary_key=True, db_column=u'ID')    

     type = models.ForeignKey(Type) 
     status = models.ForeignKey(Status) 


    #Type,Status analogous 

    #filter like this 
    selected = Person.objects.filter(type=SomeType) 
    for p in selected: 
     print p.id,p.type,p.status 
1

我建議你重新寫你的模型。所以,你的TblPerson有Tblstatus

class TblPerson(models.Model): 
    ID = models.AutoField(primary_key=True, db_column=u'ID') 
    Type = models.IntegerField(null=True, db_column=u'Type', blank=True) 
    Status = models.ForeignKey(Tblstatus, null=True, db_column=u'Status', blank=True) 
    class Meta: 
     db_table = u'tblPerson' 

class Tblstatus(models.Model): 
    ID = models.AutoField(primary_key=True, db_column=u'statStatusID') 
    Status = models.CharField(max_length=25, db_column=u'statStatus', blank=True) 
    class Meta: 
     db_table = u'tblStatus' 

使用這一點,你就能夠查詢針對Tblstatus存在這樣

TblPerson.objects.filter(Status__isnull=False) 
TblPerson對象多對一的關係