what is the difference?

11 views
Skip to first unread message

MikeKJ

unread,
Sep 7, 2018, 12:44:03 PM9/7/18
to Django users
[<Object: 1>, <Object: 2>]

and

[[<Object: 1>, <Object: 2>]]

1st came from z = Model.objects.get(name=x)

This returns the object name


2nd came from z = Model.objects.filter(name=x)

The 2nd method when you look for the id

for x in z:
print(x.id)

fails with
'QuerySet' object has no attribute 'id'

also tried

zz = Model.objects.filter(name=x)
z = z.id

same result

I understand that get just gets the first singular match but so should filter as in this instance name is unique

Andréas Kühne

unread,
Sep 7, 2018, 1:35:58 PM9/7/18
to django...@googlegroups.com
Hi,

First of all - the examples you are giving can't be correct.

z = Model.objects.get(name=x)

will only return 1 object - and will raise an exception if you get more than one result. So in this case z should be an instance of the model Model.

z = <Object: 1> 
and cannot be [<Object: 1>, <Object: 2>]

When querying the second query you should get a QuerySet as a result, because you have filtered. 

So from : z = Model.objects.filter(name=x) you would get:
[<Object: 1>]

in other words a list of 1 object (because the name was unique). Then your code:
for x in z:
   print(x.id)

should definitely work. 

If your want to do the query and just get one result (because you are querying with the unique name), you can write:
z = Model.objects.filter(name=x).first()
This way z will also be None if there isn't any object that has the name = x.

Regards,

Andréas


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c4596762-fff4-4384-9cd2-9edabb9a58f7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages