Disclaimer: I am new to python and Django, but have Drupal programming experience.
I’m following the tutorials here (http://www.djangobook.com/en/2.0/chapter05/), but I’m confused by
Publisher.objects.filter(name='Apress')
[<Publisher: Apress>]
I understand that the result is a Queryset Object, so how can I retrieve the address (or primary key) when the following approach fails?
p = Publisher.objects.filter(name='Apress')
a = p.address
'QuerySet' object has no attribute 'address'
Thanks!
The attributes are only available on the model instances. A
QuerySetis simplistically just as list of model instances, so you have to “unpack” it somehow to get at a particular instance and then the attribute on that.If you know that there’s only one of the thing you’re querying for, you should use
getinstead of filter:But, if multiple matches are returned, it will raise a
MultipleObjectsReturnedexception, and conversely, if no match is found anObjectDoesNotExistexception is raised. As a result, you need to be careful when usinggetand make sure to wrap your code in appropriatetry...exceptblocks.If you’re dealing with something where you expect more than one result, then you can either use some sort of loop structure to deal with each individual item in the
QuerySet:Or, directly pull out one item as you would with a traditional list: