我的模特是:
users = users.filter(offers__publicationDate__range=[startdate, enddate]). prefetch_related(Prefetch('offers', queryset=Offer.objects.filter(
publicationDate__range=[startdate, enddate]))).distinct()
我正在尝试在查询集上应用多个过滤器:
users = users.filter(offers__description__icontains=sometext).prefetch_related(Prefetch('offers', queryset=Offer.objects.filter(description__icontains=sometext))).distinct()
然后
ValueError: 'offers' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups.
第一个工作正常,另一个抛出以下异常:
if (offerBeginDate != None and offerEndDate != None):
b = offerBeginDate.split('-')
e = offerEndDate.split('-')
startdate = datetime.date(int(b[0]), int(b[1]), int(b[2]))
enddate = datetime.date(int(e[0]), int(e[1]), int(e[2]))
users = users.filter(offers__publicationDate__range=[startdate, enddate])
offers = offers.filter(publicationDate__range=[startdate, enddate])
if (descriptionText != None):
users = users.filter(offers__functionDescription__icontains=descriptionText.strip())
offers = offers.filter(functionDescription__icontains=descriptionText.strip())
users = users.prefetch_related('offers', Prefetch(queryset=offers))
更新
我目前的代码是:
{{1}}
有任何帮助吗?谢谢大家:)))
答案 0 :(得分:1)
您可以使用to_attr
对象的Prefetch
参数来预取其他查询集:
users = users.filter(offers__description__icontains=sometext).prefetch_related(
Prefetch('offers', queryset=Offer.objects.filter(
publicationDate__range=[startdate, enddate]), to_attr='date_offers'),
Prefetch('offers', queryset=Offer.objects.filter(description__icontains=sometext), to_attr='description_offers')).distinct()
<强> UPD 强>
如果需要动态地向预取查询集添加过滤器,可以单独定义它:
if some_case:
users = users.filter(offers__description__icontains=sometext)
offers=Offer.objects.filter(description__icontains=sometext)
if some_case_2:
users = users.filter(**conditions)
offers = offers.filter(**conditions)
users = users.prefetch_related(Prefetch('offers', queryset=offers))
现在,用户查询集中的每个用户都有两个属性:user.date_offers
和user.description_offers
。