【问题标题】:Django charfield model with db query带有数据库查询的 Django charfield 模型
【发布时间】:2013-04-22 11:21:13
【问题描述】:

我正在尝试在 hello.html 上生成一个选择菜单,其中包含来自 db 查询的列表。

我的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.

感谢您的帮助。

【问题讨论】:

    标签: python mysql django request models


    【解决方案1】:

    这正是发生的事情。选择字段的格式必须是元组的元组,如下所示:

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

    因此,为了让您的示例正常工作,nome 必须以某种符合预期类型的​​方式进行初始化,如下所示:

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

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

    我还注意到,在hello_template 中,您尝试将'name' 的值分配给html = t.render(Context({'name' : nome})) 行中的'name' 字段,因为nome 没有在方法中定义,所以这不起作用。如果你想访问 nome,你可以像 hello.nome 那样做,因为正如你定义的那样,nomehello 类中的一个类变量,所以你必须通过类来访问它。

    【讨论】:

      猜你喜欢
      • 2012-12-22
      • 1970-01-01
      • 2021-06-11
      • 2017-12-17
      • 2017-03-19
      • 1970-01-01
      • 2011-12-24
      • 2017-08-17
      • 2018-12-08
      相关资源
      最近更新 更多