[英]Django Q filter foreign key
I'm trying to create a search that takes input from two fields and searches using both.我正在尝试创建一个搜索,该搜索从两个字段获取输入并使用这两个字段进行搜索。 I know how to filter for non foreign key but trying to filter the foreign key gives the error "Related Field got invalid lookup: country"
我知道如何过滤非外键,但尝试过滤外键会出现错误“相关字段查找无效:国家/地区”
I want jobs to return the results of filtering both query and country.我希望作业返回过滤查询和国家/地区的结果。 How can I best achieve this?
我怎样才能最好地实现这一目标?
model: model:
class Job(models.Model):
title = models.CharField(max_length=50)
...
country = models.ForeignKey(
Country,
blank=True,
null=True,
help_text="Select if you're hiring within a specific "
"country",
on_delete=models.PROTECT
)
view:看法:
def jobs_search(request):
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
jobs = Job.objects.filter(site_id=get_current_site(request).id) \
.filter(paid_at__isnull=False) \
.filter(expired_at__isnull=True) \
.filter(
Q(title__icontains=cd['query'], ) |
Q(description__icontains=cd['query']) & Q(country__country__icontains=cd['country'])
) \
.order_by('-paid_at')
meta_desc = 'Search Results'
title = 'Search Results'
context = {'meta_desc': meta_desc,
'title': title,
'form': form,
'jobs': jobs}
return render(request, 'job_board/jobs_index.html', context)
you can try this你可以试试这个
from django.db.models import Q
import operator
jobs = Job.objects.all()
query = reduce(operator.and_, [ Q(author__name__icontains=x) for x in jobs ] )
jobsfilter = jobs.filter( query )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.