Django 将生成器转换为列表
我正在使用 django-voting 包,并一直在尝试获取它的管理器 get_top( )去工作。我偶然发现了一个问题 - 它生成生成器(实际上我需要从中提取数据以从数据库中选择项目),这对我来说似乎是一个问题。
经过两天的谷歌搜索和阅读论坛后,我最接近的想法是: 什么是 django 中的“生成器对象”?
它说任何生成器都可以转换为列表:
mylist=list(myGenerator)
虽然如果我将生成器转换为列表,我会收到以下错误:
'NoneType' object has no attribute '_meta'
这是我的视图和模型代码:
def main(request):
temporary = TopIssue.objects.get_top(Model=Issue, limit=10)
temp_list = list(temporary)
return render_to_response('main/index.html', temp_list)
from voting.managers import VoteManager
class TopIssue:
objects = VoteManager()
有什么想法吗?
I am using django-voting package and have been trying to get it's manager get_top() to work. I've stumbled upon one problem - it produces generator (from which actually I need to extract data to select items from database on) which seems to be a problem for me.
After spending two days of googling and reading forums, the closest think I came to was this:
What is "generator object" in django?
It says that any generator can be converted to list by:
mylist=list(myGenerator)
Althought if I do convert generator to list I get the following error:
'NoneType' object has no attribute '_meta'
Here is my view and model code:
def main(request):
temporary = TopIssue.objects.get_top(Model=Issue, limit=10)
temp_list = list(temporary)
return render_to_response('main/index.html', temp_list)
from voting.managers import VoteManager
class TopIssue:
objects = VoteManager()
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许这只是示例代码中的拼写错误,但您的
class TopIssue
并不是从 Django 模型类派生的。这也可以解释为什么您会收到有关缺少_meta
属性的错误消息。编辑:我不熟悉 django-voting,但从浏览文档来看,管理器的
get_top()
函数的第一个参数必须是 Django 模型。您可以通过继承 Django 提供的基类来实现这一点。 Django 模型在Django 模型文档中进行了解释。
因此,至少,您的
TopIssue
类应该这样声明:您的 TopIssue 类应该是一个数据库模型,并且
get_top()
函数应该返回顶部该模型的投票实例。如果您还有其他问题,请发布其余的代码(如果您发布的是完整的TopIssue
类,我觉得很奇怪 - 您缺少字段等)。Maybe this is just a typo in your example code, but your
class TopIssue
is not derived from a Django model class. That could also explain why you get the error message about the missing_meta
attribute.Edit: I'm not familiar with django-voting, but from skimming the docs, the first argument to the manager's
get_top()
function has to be a Django Model.You accomplish that by inheriting from a base class provided by Django. Django models are explained in the Django Model Documentation.
Thus at the very least, your
TopIssue
class should be declared like this:Your TopIssue class should be a database model, and the
get_top()
function is supposed to return the top voted instance of that model. Please post the rest of your code if you have further questions (it seems very strange to me if what you have posted is your completeTopIssue
class -- you are missing fields, etc.).