Search code examples
pythonmysqldjangorequestmodels

Django charfield model with db query


I am trying to generate a select menu on hello.html with a list from a db query.

My 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

and 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)

I am stuck in : ERROR testApp.hello: "title": "choices" should be a sequence of two-tuples.

Any help kindly appreciated.


Solution

  • That's exactly what happens. The format for a choices field must be a tuple of tuple, something like this:

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

    So in order to get your example to work, nome have to be initialized in some way that comply with the type expected, something like this:

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

    But be careful. You should avoid doing direct sql queries to the database, even more that kind of simple queries. There should be a better way of doing that, like encapsulating the database calling into a method or something like that.

    Also I notice that in hello_template you try to assign the value of nome to the 'name' field int the line html = t.render(Context({'name' : nome})) That won't work because nome is not defined in the method. If you want to access nome you can do it like this hello.nome because as you defined it, nome is a class variable in the hello class so you have to access it through the class.