0

我是 django 的新手。我有这个模型,在 tblperson 中,只保存了类型和状态的伪造键。如何加入所有表以显示它们的值而不是它们的 forgein 键?例如。

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'
4

2 回答 2

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 对象

TblPerson.objects.filter(Status__isnull=False)
于 2012-11-03T16:44:44.213 回答
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
于 2012-11-03T11:48:30.900 回答