我想在 django 中使用 ORM 获取两个查询数据的结果,但只显示一个数据。我该如何解决这个问题?
我的代码:
View .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”过滤掉主要表中的“major_cd”。
预期结果: 列 = Major_cd 的数据,来自主要表的描述
最佳答案
在我看来,将模型重写为 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>
关于python - 我想在 django 中使用 ORM 获取两个查询数据的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64892086/