NIKHIL RANE NIKHIL RANE -4 years ago 103
Python Question

Customize django filter model field

I have a following model

class some_model(models.Model):
some_date = models.DateTimeField()
hours = models.IntegerField()


Get a current date

temp_date = datetime.datetime.now()


Now I want filter on django field someting like this

filter_date = some_date + add timedelta(hours)


and then use filter_date in django filter

some_model.objects.filter(filter_date__gte = temp_date)


Above query possible in django?

Answer Source

You can do that with custom QuerySet. I would suggest to create custom filter method instead of overriding existing one.

Update Based on http://stackoverflow.com/a/33916628/3627387 You can achieve it with using extra

class CustomQuerySet(models.QuerySet):
    def date_filter(self):
        # using
        return self.extra(where=["some_date + hours * INTERVAL '1 hour' >= %s"], params=[datetime.now()])

class some_model(models.Model):
    some_date = models.DateTimeField()
    hours = models.IntegerField()

    objects = CustomQuerySet.as_manager()

# And then in your code
some_model.objects.date_filter()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download