Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在django中显示从模型管理器返回的数据_Mysql_Django_Django Models - Fatal编程技术网

Mysql 在django中显示从模型管理器返回的数据

Mysql 在django中显示从模型管理器返回的数据,mysql,django,django-models,Mysql,Django,Django Models,我在Django中使用MySQL,无法看到在模型管理器中执行的查询返回的数据 页面与表一起呈现,边框和分页正在工作,但是,表中没有显示任何字段值 我猜在返回查询结果和用html表示查询结果之间需要一步,但我被难住了 在上下文中,我正在设置我的管理器,以便执行比Django提供的更复杂的查询 我以一些使用模型管理器和一个相当简单的查询作为开始的例子-。。我在本网站之外研究过的众多参考文献之一: 在花了很多时间搜索之后,我相信这里有人能帮上忙。提前谢谢 以下是模型管理器: class Electio

我在Django中使用MySQL,无法看到在模型管理器中执行的查询返回的数据

页面与表一起呈现,边框和分页正在工作,但是,表中没有显示任何字段值

我猜在返回查询结果和用html表示查询结果之间需要一步,但我被难住了

在上下文中,我正在设置我的管理器,以便执行比Django提供的更复杂的查询

我以一些使用模型管理器和一个相当简单的查询作为开始的例子-。。我在本网站之外研究过的众多参考文献之一:

在花了很多时间搜索之后,我相信这里有人能帮上忙。提前谢谢

以下是模型管理器:

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 %}
{%for elect in electpage%}
{{elect.first_name | lower | capfirst}}
{{elect.last|u name | lower | capfirst}}
{{elect.current_party}
{{elect.street_number}{{{elect.unit}}
{{elect.street_name | lower | capfirst}{{{elect.street_name | lower | capfirst}}{{elect.street_name | 2 | lower | capfirst}
{{elect.city | lower | capfirst}}
{%endfor%}

您的自定义管理器方法没有返回选举对象;它返回表示数据库行的元组。因此,您不能按字段名引用模板中的结果,就像它们是对象一样


实际上,这不是管理者的职责;您的管理者方法应始终返回查询集。

感谢您的见解

我做了一些更改,并使其工作,但没有使用模型管理器(目前)

  • 现在,我删除了models.py中对我的模型管理器的引用- (我可以在以后的迭代中/重构时添加)
  • 使用对数据库的原始sql调用,我成功地处理了一个相当简单的查询结果(在html中填充了正确的数据-不需要更改html)
    • 我将此作为参考:
以下是增强的视图,它使事情正常工作:

def vhistfun(request):
election_table = Election.objects.raw("""
                SELECT *
            FROM
                newvoterproject.fullvh vh1
            WHERE
                vh1.city = 'Glocester'
                    AND (vh1.current_party = 'r' or vh1.current_party = 'u') 
                    GROUP BY vh1.city , 
                    vh1.street_name ,  
                    CONVERT(SUBSTRING_INDEX(vh1.street_number,'-',-1),UNSIGNED INTEGER)  , 
                    vh1.unit
            ;
                    """)
party_list=('r','u')
town_list=('Glocester')
query_information ='Voters in the 2012 Presidential Election (election_3) and either the 2008 Presidential Election (election_8)or the 2012 Presidential Primary (election_5)'

paginator = Paginator(list(election_table), 10) # NOTE > this was changed from paginator = Paginator(election_table , 25)
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,
           'party_list': party_list,
           'town_list': town_list,
           'query_information ': query_information
           }
return render(request, 'elections/electable.html', context)
请注意/注意-使用objects.raw导致分页出现此问题:

object of type 'int' has no len()
我在这里找到了修复方法:

目前,我正在用数据填充我的表,并将继续进行我的项目所需的更高级查询

我暂时不回答这个问题。
虽然我使用raw成功地获得了所需的数据,但它并没有解决所提出的问题——为什么模型管理器中的查询不能在html上正确地显示数据

那么,有没有一种方法可以将结果转换为一组iterable对象呢?django中的查询集功能无法满足我的需要;问题不在于for循环,而是您按名称引用每个字段,而您只有一个值元组。但是,您可能应该使用queryset方法,而不是直接调用游标,因为它确实映射到字段名。