开发者

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

开发者 https://www.devze.com 2023-02-05 01:44 出处:网络
employees = Employee.objects.filter(age=23, sex=\'female\') This would return a queryset. If 开发者_JAVA百科I assume this queryset only contains one result, how to return that object directly?
employees = Employee.objects.filter(age=23, sex='female')

This would return a queryset.

If 开发者_JAVA百科I assume this queryset only contains one result, how to return that object directly?

Is there any way like using 'get'?


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?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号