【问题标题】:Fetch data from multiple tables in django views从 django 视图中的多个表中获取数据
【发布时间】:2015-11-25 22:08:54
【问题描述】:

在 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'`

【问题讨论】:

    标签: django django-forms django-views


    【解决方案1】:

    以下是您只需一次数据库调用即可完成此操作的方法:

    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”方法更短的方法来引用外来对象,你可以设置一个related_name,比如

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

    然后将workeraccount_set替换为waccount

    【讨论】:

      【解决方案2】:

      你可以这样做:

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

      【讨论】:

      • 我收到错误,因为 'QuerySet' 对象没有属性 'workeraccount',查询已执行:obj=Workerprofile.objects.all() workavail=obj.workeraccount.objects.all()。跨度>
      • 你有制表符补全吗?如果你这样做 workprofile. + tab 你会看到什么?我也更新了答案。
      猜你喜欢
      • 2018-12-22
      • 2020-08-21
      • 1970-01-01
      • 2017-03-22
      • 2022-08-20
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多