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

前端 未结 1 964
抹茶落季
抹茶落季 2021-02-02 11:34
employees = Employee.objects.filter(age=23, sex=\'female\')

This would return a queryset.

If I assume this queryset only contains one result, h

相关标签:
1条回答
  • 2021-02-02 12:32

    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 讨论(0)
提交回复
热议问题