gpt4 book ai didi

django - 从 Django View 中的多个表中获取数据

转载 作者:行者123 更新时间:2023-12-02 04:46:41 28 4
gpt4 key购买 nike

在 Django View 中,我想获取任何特定 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'`

最佳答案

你可以这样做:

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)
...

关于django - 从 Django View 中的多个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318613/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com