almost a beginner
almost a beginner

Reputation: 1632

Django get months from models.DateTimeField

Is it possible to filter a models.DateTimeField but only get the month in the filter object?

The field is:

time_stamp = models.DateTimeField(
            default=timezone.now)

When I filter it, this is what I get:

[datetime.datetime(2016, 9, 22, 15, 2, 48, 867473, tzinfo=), datetime.datetime(2016, 9, 22, 15, 4, 22, 618675, tzinfo=), datetime.datetime(2016, 9, 22, 15, 5, 20, 939593, tzinfo=)]

The filter returns 3 rows, but clearly there is too much information. I only require the months, and maybe the year.

How can I achieve this?

Any help or direction would be appreciated,

Thanks

Upvotes: 2

Views: 5952

Answers (2)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15400

If you are using django 1.10.x there is Extract db function

from django.db.models.functions import Extract

months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'month')).values_list('month_stamp', flat=True)

For django 1.9.x

from django.db.models import Func

def Extract(field, date_field='DOW'):
    template = "EXTRACT({} FROM %(expressions)s::timestamp)".format(date_field)
    return Func(field, template=template)

months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'month')).values_list('month_stamp', flat=True)

Upvotes: 3

Windsooon
Windsooon

Reputation: 7140

You can use propety:

Class your_model(models.Model):

    time_stamp = models.DateTimeField(
        default=timezone.now)

    @property
    def _get_year(self):
        return self.time_stamp.strftime("%Y-%m")

    year = property(_get_year) #EDIT

Upvotes: 3

Related Questions