簡體   English   中英

Django annotate返回了不止一個

[英]Django annotate returned more than one

user = get_object_or_404(
    (User.objects
        .annotate(company_name=F('usercompany__company__company_name'))
        .annotate(project=F('team__vacancy__name'))),
    email=request.GET.get('user_email')
)

我有錯誤:

proj.models.MultipleObjectsReturned: get() returned more than one User -- it returned 2!

如何更改.annotate(project=F('team__vacancy__name')))以獲取所有內容。

您可以使用prefetch_related來獲取空缺。 根據您的模型,查詢集將類似於:

User.objects.annotate(company_name=F('usercompany__company__company_name')
    ).select_related('team'
    ).prefetch_related('team__vacancy')

然后你可以得到這些名字:

names = [v.name for v in user.team.vacancy_set.all()]

當你使用get_object_or_404它需要一個對象。 否則,它返回HTTP狀態代碼404(NOT FOUND)。

如果您希望從查詢中返回多個對象,那么您應該使用get_list_or_404

from django.shortcuts import get_list_or_404

正如文檔中所解釋的那樣, get_list_or_404get_object_or_404之間的區別等同於.filter().get()之間的區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM