我想在 django 中使用 ORM 获得两个查询数据的结果

I want to get result of two query data using ORM in django

我想在 django 中使用 ORM 获取两个查询数据的结果,但只显示一个数据。我该如何解决?

我的代码:

views.py

def home(request):
    
    codes, descrp = Major.objects.raw('SELECT p.major_cd, m.description FROM percentages p, major m WHERE p.major_cd = m.major_cd;')
    context = { 
               "codes": codes,
               "descrp": descrp
    }
 return render(request, "website/index.html" , context )

index.html

<select class="form-control select2">
   <option>Select Major Head</option> 
   {% for cd, ds in codes, descrp %}
    <option> {{ cd, ds }} </option> 
    {% endfor %} 
    </select>

车型

class Major(models.Model):
    major_cd = models.IntegerField(primary_key=True)
    description = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'major'

class Percentages(models.Model):
    major_cd = models.IntegerField(primary_key=True)
    percentage = models.CharField(max_length=5, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'percentages'

我想根据 'major_cd' 的百分比 table.

过滤掉主要 table 中的 'major_cd'

预期结果: 列 = major_cd 的数据,主要 table

的描述

你可以使用Q,from django.db.models import Q.

例如,你可以让它像.. descrp = Major.objects.filter(Q(major_cd=.major_cd) & Q(m_description=m.description))

在我看来,将模型重写为ForeignKey可能会更好,这样在Django中查询更方便:

class Major(models.Model):
    major_cd = models.IntegerField(primary_key=True)
    description = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'major'

class Percentages(models.Model):
    major_cd = <b>models.OneToOneField(</b>
        Major,
        on_delete=models.CASCADE,
        primary_key=True,
        <b>db_column='major_cd'</b>
    <b>)</b>
    percentage = models.CharField(max_length=5, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'percentages'

完成后,我们可以查询:

def home(request):
    <b>majors</b> = Major.objects.filter(<b>percentage__isnull=False</b>)
    context = { 
        'majors': majors
    }
    return render(request, 'website/index.html', context)

在模板中,我们可以用以下方式渲染它:

<select class="form-control select2">
  <option>Select Major Head</option> 
  {% for major in majors %}
    <option><b>{{ major.pk }}: {{ major.description }}</b></option> 
  {% endfor %} 
</select>