从django视图中的多个表中获取数据

时间:2015-08-31 19:32:03

标签: django django-forms django-views

在Django视图中,我想获取任何特定wid = 1的所有细节(Workeraccount.location,Workeravail.date,Workerprofile。*)。

SQL查询:

select * from Workeraccount,Workeravail,Workerprofile where Workerprofile.wid=1 and Workerprofile.wid=Workeravail.wid and Workeraccount.wid=Workerprofile.wid;

相应的型号如下:

class Workeraccount(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid', unique=True)
    location = models.ForeignKey(Location, db_column='location')
    class Meta:
        managed = False
        db_table = 'workerAccount'

class Workeravail(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid')
    date = models.DateField()
    class Meta:
        managed = False
        db_table = 'workerAvail'

class Workerprofile(models.Model):
    wid = models.SmallIntegerField(primary_key=True)
    fname = models.CharField(max_length=30)
    mname = models.CharField(max_length=30, blank=True, null=True)
    lname = models.CharField(max_length=30)
    gender = models.CharField(max_length=1)
    age = models.IntegerField()
    class Meta:
        managed = False
        db_table = 'workerProfile'`

2 个答案:

答案 0 :(得分:0)

你可以这样做:

workprofile = Workerprofile.objects.filter(id=1).first()
all_worker_avails = workprofile.workeravail_set.all()
all_workeraccounts = workprofile.workeraccount_set.all()

由于WorkeraccountWorkeravail通过Workerprofile相关联,您可以轻松获得一个查询集 - 您将需要两个单独的查询集。

您还可以执行以下操作:

all_worker_avails = Workeravail.objects.filter(wid=workprofile)
...

答案 1 :(得分:0)

以下是仅使用一次数据库调用的方法:

workprofile = Workerprofile.objects.get(pk=1)
    .select_related('workeravail_set', 'workerprofile_set')

这将立即为您提取所有数据,然后可以使用:

workprofile.workerprofile_set.location #Gets the Workeraccount.location
workprofile.workeravail_set.date       #Gets the Workeravail.date
workprofile.fname                      #Example of Workerprofile.*

顺便说一下,如果你想要一个比“* _set”方法更短的引用外来对象的方法,你可以设置一个相关的名称,如

class Workeraccount(models.Model):
    wid = models.ForeignKey('Workerprofile', db_column='wid', unique=True, related_name='waccount')
    ...

然后将workeraccount_set替换为waccount