从django视图中的多个表获取数据
在Django视图中,我希望获取任何特定wid=1的所有详细信息(Workeraccount.location、Workeravail.date、Workerprofile.*) SQL查询:从django视图中的多个表获取数据,django,django-forms,django-views,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
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'`
您可以这样做:
workprofile = Workerprofile.objects.filter(id=1).first()
all_worker_avails = workprofile.workeravail_set.all()
all_workeraccounts = workprofile.workeraccount_set.all()
由于Workeraccount
和Workeravail
通过Workerprofile
关联,因此您可以轻松获得一个查询集-您将需要两个单独的查询集
您还可以执行以下操作:
all_worker_avails = Workeravail.objects.filter(wid=workprofile)
...
以下是只需一个数据库调用即可完成此操作的方法:
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.*
另外,如果希望引用外来对象的方式比“*\u set”方法短,可以设置相关的\u名称,如
class Workeraccount(models.Model):
wid = models.ForeignKey('Workerprofile', db_column='wid', unique=True, related_name='waccount')
...
然后将
workeraccount\u set
替换为waccount
我收到错误,因为'QuerySet'对象没有'workeraccount'属性,执行的查询是:obj=Workerprofile.objects.all()workavail=obj.workeraccount.objects.all()。是否有制表符完成?如果您使用workprofile.
+tab,您会看到什么?我也更新了我的答案。