Python Django-charfield模型与数据库查询
我试图在Python Django-charfield模型与数据库查询,python,mysql,django,request,models,Python,Mysql,Django,Request,Models,我试图在hello.html上生成一个选择菜单,其中包含来自db查询的列表 Mymodels.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
hello.html
上生成一个选择菜单,其中包含来自db查询的列表
Mymodels.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
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)
和my views.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
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”应该是两个元组的序列。
非常感谢您的帮助。事情就是这样。选项字段的格式必须是元组中的元组,如下所示:
CHOICES=(
('f','foo'),
('b','bar'),
)
nome=((x,x) for x in db.query(q))
因此,为了让示例正常工作,nome
必须以符合预期类型的方式进行初始化,如下所示:
CHOICES=(
('f','foo'),
('b','bar'),
)
nome=((x,x) for x in db.query(q))
但是要小心。您应该避免对数据库进行直接的sql
查询,更不要进行那种简单的查询。应该有更好的方法,比如将数据库调用封装到方法或类似的东西中
我还注意到,在hello_template
中,您试图将nome
的值分配给html=t.render(Context({'name':nome}))行中的'name'
字段,该字段将不起作用,因为nome
未在该方法中定义。如果你想访问nome,你可以这样做hello.nome
,因为正如你定义的那样,nome
是hello
类中的一个类变量,所以你必须通过类来访问它