NOTE: The query in your PHP snippet does not even match the one in your Django snippet to start with. The PHP one does a SELECT * FROM data
but the Python one does a SELECT * FROM data WHERE id = 1
, so I'm gonna go ahead and assume you intended Foo.objects.all()
instead of Foo.objects.get(id=1)
. If you didn't, then please fix your question, and also simply remove the looping part of the code snippets below. Also, you should find a better name for the variable datalist
if it's going to contain just one item not a list as the name suggests, which was a source of confusion for me initially.
You haven't really described very clearly what your goal is, but here are a few options that might potentially match your needs:
for obj in datalist:
print "%s => %s" % (obj.id, obj)
...or if you want to iterate over all key-value pairs of all objects:
for obj in datalist:
print "OBJECT %s" % obj.id
for field in Foo._meta.fields:
print " %s => %s" % (field.name, getattr(obj, field.name)
...or you can use the django.forms.models.model_to_dict
helper to convert the objects to dictionaries:
from django.forms.models import model_to_dict
for obj in datalist:
print "OBJECT %s" % obj.id
for key, value in model_to_dict(obj_as_dict).items():
print " %s => %s" % (key, value)