简体   繁体   中英

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:

  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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM