views:

25

answers:

2

I have been able to get my database queries to work properly for deleting existing entries and also adding new entries to the database but I am completely stumped as to why I am unable to retrieve anything from my database. I am trying a query such as:

from web1.polls.models import Poll
retquery = Poll.objects.all()
print retquery
--prints: "[ ]"

Also, if I try this, it just returns "poll object"

from web1.polls.models import Poll
retquery = Poll.objects.all()[0]
print retquery
--prints: "poll object"

I have looked at everything and there are definitely entries in the database, I have tried this with a number of different models where everything else is working otherwise so I don't know what I can do at this point, any advice is greatly appreciated

A: 

I finally figured this out, I am leaving this up since this can be really confusing for someone fairly new to Python, such as myself, as Django's docs don't make this entirely clear, I'm used to printing out an object and having it list everything in it but for some reason the type of object that is returned is not in such a format that doing this will work, so you need to take the resulting variable from the query and add the name of the field to the end in order to access it, such as:

If I have a field named "question" that I want to retrieve:
retquery = Poll.objects.all()
print retquery.question

This will work, whereas the way I was doing it before it just printed nothing making me think that the returned object was empty

Rick
+1  A: 

if you have provide well __unicode__ method to your model, you won't have such problem...

http://www.djangoproject.com/documentation/models/str/
Tumbleweed
Thanks, yeah I saw this before but it was giving me some error so I didn't use the __unicode__ method, I didn't realize it would have led to this, however, thanks for the tip
Rick