Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a single model object using multiple ORM lookup parameters

Tags:

employees = Employee.objects.filter(age=23, sex='female') 

This would return a queryset.

If I assume this queryset only contains one result, how to return that object directly?

Is there any way like using 'get'?

like image 386
user469652 Avatar asked Jan 18 '11 09:01

user469652


1 Answers

Actually, you can pass multiple lookup parameters in QuerySet's get() method. So how about?

try:     employee = Employee.objects.get(age=23, sex='female') except Employee.DoesNotExist:     # no employee found except Employee.MultipleObjectsReturned:     # what to do if multiple employees have been returned? 
like image 142
Haes Avatar answered Dec 11 '22 00:12

Haes