2013-04-28 71 views
3

我想用db查询中的列表生成hello.html的选择菜单。用db查询的Django charfield模型

models.py

class hello(models.Model): 
    q = """ 
    SELECT * FROM ZONAS 
    WHERE cod_zona = 1 
    """ 
    db.query(q) 
    nome = db.query(q) 

    title = models.CharField(max_length=3, choices=nome) 

    def __unicode__(self): 
     return self.name 

my views.py

def contato(request): 
    form = hello() 
    return render_to_response(
     'hello.html', 
     locals(), 
     context_instance=RequestContext(request), 
    ) 

def hello_template(request): 
    form = hello() 
    t = get_template('hello.html') 
    html = t.render(Context({'name' : nome})) 
    return HttpResponse(html) 

我被困在:ERROR testApp.hello: "title": "choices" should be a sequence of two-tuples.

任何帮助,恳请赞赏。

回答

2

这正是发生的情况。对于选择字段的格式必须是元组的元组,像这样:

CHOICES=(
    ('f','foo'), 
    ('b','bar'), 
) 

因此,为了让您的示例工作,nome必须以某种方式与期望的类型符合被初始化,东西像这样:

nome=((x,x) for x in db.query(q)) 

但要小心。你应该避免直接对数据库进行sql查询,甚至可以进行更简单的查询。应该有更好的方法来做到这一点,比如将数据库调用封装到方法或类似的东西中。

此外,我注意到,在hello_template您尝试的nome值分配给'name'场INT行html = t.render(Context({'name' : nome}))因为nome没有方法中定义这是行不通的。如果你想访问nome,你可以这样做hello.nome,因为如你所定义的,nomehello类中的类变量,所以你必须通过类来访问它。