Tuesday, October 27, 2015

Re: bug: mymodel.objects.first().get('id',None) AttributeError: 'NoneType' object has no attribute 'get'

> Den 27. okt. 2015 kl. 04.01 skrev gugeshi250@gmail.com:
>
> hi ,how are you
>
> i run
>
> myid=mymodel.objects.first().get('id',None)
>
> If there is a record, it's ok
>
> If there is no record, error info:
>
> AttributeError: 'NoneType' object has no attribute 'get'
>
>
> If there is a record,Can you let it return an empty dictionary,


I don't see how .get() would not throw an AttributeError if first() returns a mymodel instance, but here's one solution to your problem:

myid = mymodel.objects.values('id').first() or {}


Erik

--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/B464C21A-55DC-475C-B7F4-CCA679219AD8%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment