Hi,
print(x.id)
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
Den fre 7 sep. 2018 kl 18:44 skrev MikeKJ <mike.jones@paston.co.uk>:
--[<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
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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/CAK4qSCct81WvkB9_SiUphK1h4VyCPh%3DocRihU-Ah5_nP6zvs5g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment