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

17 views
Skip to first unread message

guges...@gmail.com

unread,
Oct 27, 2015, 7:22:50 AM10/27/15
to Django users
 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,

thank you 

Erik Cederstrand

unread,
Oct 27, 2015, 7:30:49 AM10/27/15
to Django Users
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
Reply all
Reply to author
Forward
0 new messages