[英]Django ORM: Filter with OR not returning object
以下代碼未返回對象,但應“返回”。 我通過的手機,電子郵件和激勵ID正確匹配,那么我做錯了什么?
return Recipient.objects.filter(
models.Q(mobile=mobile,
email=email,
incentive__id__exact=incentive_id) |
models.Q(friends_mobile=mobile,
friends_email=email,
incentive__id__exact=incentive_id)
).order_by(
'-date_created')[:1].get()
使用.get()
有問題。 如果僅將QuerySet與一個對象一起使用,它將返回一個對象,但如果有更多對象,它將引發MultipleObjectsReturned
錯誤;如果QuerySet為空,則將引發DoesNotExist
錯誤。
因此,問題很可能是不適用於您所需的特定條件的QuerySet。 解決方案? 返回默認值。
最后,您可以使用[0]
而不是限制一個對象然后再獲取它,而且,如@pythonishvili所述,您可以對激勵進行預過濾。 總結起來,它看起來應該像這樣(為了更好的可讀性,我將查詢分成多行):
qs = Recipient.objects.filter(incentive__id__exact=incentive_id) #common filter
qs = qs.filter(models.Q(mobile=mobile, email=email) |
models.Q(friends_mobile=mobile, friends_email=email))
qs = qs.order_by('-date_created')
return qs[0] if qs else None #or any other default you'd like to use
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.