开发者

Django debug error

开发者 https://www.devze.com 2022-12-25 02:01 出处:网络
I have the following in my model: class info(models.Model): add = models.CharField(max_length=255) name = models.CharField(max_length=255)

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.Al开发者_JS百科so how to query for only one field instead of selecting all like select name from info.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消