[Fixed]-How to search in django models if some fields are not required

0👍

Well, I have a really ridicules situation. In my model I make some fields blank=True and forgot to do makemigrations! So don’t forget to make migrations

1👍

Following is usually handy when you have to build filters from long list of form data.

import operator
from django.db.models import Q
filter_list = [Q(name=name)]
if surname:
    filter_list.append(Q(surname=surname))

YourModel.objects.filter(reduce(operator.and_, filter_list))

0👍

You can build a QS in parts:

def you_view(request, name, surname):
    # ... Get you filter parameters, just an example.
    qs = MyModel.objects.filter(name=name)
    if surname:
        qs = qs.filter(surname=surname)
    # work with qs

This will filter by surname only if there is a surname variable in your view.

👤Gocht

Leave a comment