2013-04-28 4 views
3

db 쿼리의 목록으로 hello.html에 선택 메뉴를 생성하려고합니다. 내 models.pydb 쿼리를 사용하는 장고 charfield 모델

:

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이 방법에 정의되어 있지 않기 때문에 작동하지 않습니다 라인 html = t.render(Context({'name' : nome}))하는 int 'name' 필드에 nome의 값을 할당하려고 것을 알 수 있습니다. nome에 액세스하고 싶다면 nomehello 클래스의 클래스 변수이므로 클래스를 통해 액세스해야하기 때문에 hello.nome과 같이 할 수 있습니다.