[Django]-How to set default value in Django while filtering objects from models

7👍

You can make a manager method for this.

class ProfileManager(models.Manager):
    def myfilter(self, **filters):
        filters = {k:v for k,v in filters.items() if v is not None}
        qs = self.get_queryset()
        return qs.filter(**filters)

Be sure to set the manager in the model

class Profile(models.Model):
    objects = ProfileManager()
    # the rest of the model

Then you can pass name age and gender (or any other column) to objects.myfilter and it will ignore any value of None.

# assume the following values are retrieved
# name = 'Shashank'
# age = None
# gender = None

qs = Profile.objects.myfilter(name=name, age=age, gender=gender)

The qs here should be the same as objects.filter(name=name)

👤sytech

2👍

Probably not the best solution but I’ve done this way : you chain the filter while checking if the value is not None.

qs = Profile.objects.all()
if name:
    qs = qs.filter(name=name)
if age:
    qs = qs.filter(age=age)
if gender:
    qs = qs.filter(gender=gender)

Or maybe this answer can help you.

Leave a comment