[Answer]-Django many to many query with null form and model values

1đź‘Ť

âś…

def TrademanLookup(request)
    if request.method == 'POST':      
        if form.is_valid()
            discipline=form.cleaned_data['discipline']
            language=form.cleaned_data['language']
            query = []
            if disciplines:
                query.append(Q(discipline__in=discipline))
            if language:
                query.append(Q(language__in=language))

            if query:    
                tradesman_return=Tradesman.objects.filter(*query)
            else:
                tradesman_return=Tradesman.objects.all()

            #...work with returned data...

NB : it’s considered GoodPractice(TM) to use plural forms for collections (should really be “disciplines” and “languages” in both the Trademan model and the form.

NB2 : the convention is to use all_lower_with_underscore names for functions, so your view should be named “trademan_lookup”

Leave a comment