【发布时间】:2016-05-03 19:57:49
【问题描述】:
我将 MySQL 与 Django 一起使用,但无法查看在模型管理器中执行的查询返回的数据。
页面与表格一起呈现,边框和分页正在工作,但是表格中没有出现任何字段值。
我猜在返回查询结果和以 html 形式呈现之间需要一个步骤,但我很难过。
对于上下文,我正在设置我的经理,以便我可以执行比 Django 提供的更复杂的查询。
我遵循了一些使用模型管理器的示例,并以一个相当简单的查询作为开始 - .. 我在本网站之外研究过的众多参考资料之一:https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers
在花了很多时间搜索之后,我相信这里有人可以提供帮助。提前致谢!!
这里是模型管理器:
class ElectionsManager(models.Manager):
def is_active(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT *
FROM
newvoterproject.fullvh vh1
WHERE
vh1.city = 'Glocester' and
vh1.current_party = 'd'
group by
vh1.city,
vh1.street_name,
vh1.street_name_2,
vh1.street_number,
vh1.unit
;""")
result_list = cursor.fetchall()
return result_list
这里是模型的一个片段:
class Election(models.Model):
voter_id = models.CharField(primary_key=True, max_length=25)
last_name = models.CharField(max_length=50, blank=True, null=True)
first_name = models.CharField(max_length=50, blank=True, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
current_party = models.CharField(max_length=50, blank=True, null=True)
street_number = models.CharField(max_length=50, blank=True, null=True)
street_name = models.CharField(max_length=50, blank=True, null=True)
street_name_2 = models.CharField(max_length=50, blank=True, null=True)
unit = models.CharField(max_length=50, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=50, blank=True, null=True)
zip_code = models.CharField(max_length=50, blank=True, null=True)
zip_code_4 = models.CharField(max_length=50, blank=True, null=True)
precinct = models.CharField(max_length=50, blank=True, null=True)
status = models.CharField(max_length=50, blank=True, null=True)
objects = ElectionsManager() # model manager
class Meta:
managed = False
verbose_name = 'Election'
verbose_name_plural = 'Elections'
db_table = 'fullvh'
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
从视图调用模型管理器:
def vhistfun(request):
election_table = Election.objects.is_active()
paginator = Paginator(election_table , 25) # Show 25 contacts per page - may want to change this to READ 25 at a time...
page = request.GET.get('page')
try:
electpage = paginator.page(page)
except PageNotAnInteger:
electpage = paginator.page(1)
except EmptyPage:
electpage = paginator.page(paginator.num_pages)
context = {'electpage': electpage,
}
return render(request, 'elections/electable.html', context)
.. 以及处理结果的 html 片段
{% for elect in electpage %}
<tr id="voterrowclass" class="">
<td> {{ elect.first_name|lower|capfirst }} </td>
<td> {{ elect.last_name|lower|capfirst }} </td>
<td> {{ elect.current_party}} </td>
<td> {{ elect.street_number}} {{ elect.unit}} </td>
<td> {{ elect.street_name|lower|capfirst}} {{ elect.street_name_2|lower|capfirst}} </td>
<td> {{ elect.city|lower|capfirst}} </td>
</tr> <!-- # model data sent from view -->
{% endfor %}
【问题讨论】:
标签: mysql django django-models