views:

54

answers:

1

I have the following in my model:

 class info(models.Model):
     add = models.CharField(max_length=255)
     name = models.CharField(max_length=255)

An in the views when i say info_l = info.objects.filter(id=1) logging.debug(info_l.name)

i get an error saying name doesnt exist at debug statement. 'QuerySet' object has no attribute 'name' 1.How can this be resolved. 2.Also how to query for only one field instead of selecting all like select name from info.

+2  A: 

1. Selecting Single Items

It looks like you're trying to get a single object. Using filter will return a QuerySet object (as is happening in your code), which behaves more like a list (and, as you've noticed, lacks the name attribute).

You have two options here. First, you can just grab the first element:

info_l = info.objects.filter(id=1)[0]

You could also use the objects.get method instead, which will return a single object (and raise an exception if it doesn't exist):

info_l = info.objects.get(id=1)

Django has some pretty good documentation on QuerySets, and it may be worth taking a look at it:
Docs on using filters
QuerySet reference

2. Retrieving Specific Fields

Django provides the defer and only methods, which will let you choose specific fields from the database, rather than fetching everything at once. These don't actually prevent the fields from being read; rather, it loads them lazily. defer is an "opt-in" mode, which lets you specify what fields should be lazily loaded. only is "out-out" -- you call it, and only the fields you pass will by eagerly loaded.

So in your example, you'd want to do something like this:

info_l = info.objects.filter(id=1).only('name')[0]

Though with a model as simple as the example you give, I wouldn't worry much at all about limiting fields.

ShZ
Thanks for the reply.What i meant to say is for ex:select name from info; instead of doing a select * from info;Thanks for the reply
Hulk
Ah, I understand now. I've updated the answer.
ShZ
Thanks very much
Hulk
@ShZ: +1 for thoughtful, complete answer pointing to the docs. We need more answers like these. :-)
celopes