django-modelsdjango-viewsdjango-ormqobject

Is there a way to concatenate with q objects?


I've been struggling with implementing this. I'm trying to build a dynamic queryset where the conditions will be based on user entry. A user can decide to search by first or last name or a combination of both. If searching by only last name the firstname query will not be added to the queryset. I currently have it working for a search with all the fields entered.

results = documents.objects.filter(
    Q(f_filer__filer_first_name__istartswith=request.GET.get('first_name', 
'')) & (f_filer__filer_last_name__istartswith=request.GET.get('last_name', 
'')) & 
Q(f_office__o_office_name__istartswith=request.GET.get('office_name', ''))
    & Q(f_doc_year__exact=request.GET.get('report_year', ''))
    & Q(f_report_id__exact=request.GET.get('filing_type', ''))       
    ).values('f_filer__filer_first_name',
          'f_filer__filer_last_name',
          'f_office__o_office_name',
          'f_date_received',
          'f_start_travel_date',
          'f_end_travel_date',
          'f_doc_year',
          'f_report__r_title')

Solution

  • You can just concatenate filter like this:

    queryset = documents.objects.all()
    
    first_name = request.GET.get('first_name')
    last_name = request.GET.get('last_name')
    
    if first_name:
        queryset = queryset.filter(first_name=first_name)
    if last_name:
        queryset = queryset.filter(last_name=lastname)
    

    I have shorten the filter arguments for simplifying the example