php - Django: how to get a model's keys -
so trying world of python , django. coming php, many things similar, have hard time figuring out how following.
in php this:
$q = $this->db->query('select * data'); foreach ($q->result_array() $key => $value) { switch ($key) { [...] } }
now, question is: how can accomplish similar in django / python? have setup:
from index.models import foo def index(request): datalist = foo.objects.get(id=1)
and what?
note: query in php snippet not match 1 in django snippet start with. php 1 select * data
python 1 select * data id = 1
, i'm gonna go ahead , assume intended foo.objects.all()
instead of foo.objects.get(id=1)
. if didn't, please fix question, , remove looping part of code snippets below. also, should find better name variable datalist
if it's going contain 1 item not list name suggests, source of confusion me initially.
you haven't described goal is, here few options might potentially match needs:
for obj in datalist: print "%s => %s" % (obj.id, obj)
...or if want iterate on key-value pairs of objects:
for obj in datalist: print "object %s" % obj.id field in foo._meta.fields: print " %s => %s" % (field.name, getattr(obj, field.name)
...or can use django.forms.models.model_to_dict
helper convert objects dictionaries:
from django.forms.models import model_to_dict obj in datalist: print "object %s" % obj.id key, value in model_to_dict(obj_as_dict).items(): print " %s => %s" % (key, value)
Comments
Post a Comment