django-database-functions

How to annotate a difference of datetime in days

☆樱花仙子☆ 提交于 2019-12-01 11:15:07
I have a Booking model that has start and end datetime fields. I want to know how many days a booking covers. I can do this in Python but I need this value for further annotations. Here's what I've tried: In [1]: Booking.objects.annotate(days=F('end')-F('start'))[0].days Out[1]: datetime.timedelta(16, 50400) There are a few problems here: I want an integer (or other number type I can use in calculations) of days as the output, not a timedelta. Setting output_field doesn't do anything meaningful here. My sums are based on date times . Subtractions like this, without removing the time could lead

How to make/use a custom database function in Django

谁说我不能喝 提交于 2019-11-27 03:37:49
问题 Prologue: This is a question arising often in SO: Equivalent of PostGIS ST_MakeValid in Django GEOS Geodjango: How to Buffer From Point Get random point from django PolygonField Django custom for complex Func (sql function) and can be applied to the above as well as in the following: Django F expression on datetime objects I wanted to compose an example on SO Documentation but since it got shut down on August 8, 2017, I will follow the suggestion of this widely upvoted and discussed meta