Customize django filter model field

I have the following model

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

Get current date

temp_date = datetime.datetime.now()

Now I want the filter on the django field to look like

filter_date = some_date + add timedelta(hours)

and then use filter_date in django filter

some_model.objects.filter(filter_date__gte = temp_date)

Is it possible to execute a request in django?

+4
source share
3 answers

You can do this with customQuerySet . I would suggest creating your own filtering method instead of overriding the existing one.

Update Based on fooobar.com/questions/1658663 / ... You can achieve this withextra

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()
0
source

Another elegant way is to create a DataBase function.

, , . - , .

from django.db import models

class SomeModel(models.Model):
    date_start = models.DateTimeField()
    duration = models.FloatField()

DataBase:

from django.db.models.expressions import Func
from django.db.models import DateTimeField


class Interval(Func):
    function = 'INTERVAL'
    template = "(%(expressions)s * %(function)s '1 %(phylum)s')"

    def __init__(self, expression, phylum, **extra):
        output_field = extra.pop('output_field', DateTimeField())
        super(Interval, self).__init__(expression, output_field=output_field, phylum=phylum, **extra)

. Interval F ('field_name') Value() Python. : "", "", "", "".

objs = (SomeModel.objects.annotate(date_end=F('date_start') + Interval(F('duration'), 'hour')).
filter(date_end__lte=datetime.datetime.now(pytz.utc)))
  • : Django == 1.8.15, Postgres: 9.4.5

  • Postgres, : 'as_postgresql', 'as_oracle'

+4

, , - , filter_date .

, , , some_date , hours . :

some_model.objects.filter(
    some_date__gte=datetime.datetime.now()-datetime.timedelta(hours=hours))
0

Source: https://habr.com/ru/post/1658660/


All Articles