Using dateadd in django filter

后端 未结 1 1773

I have a model that defines subscription periods by start date and duration (in days):

class SubscriptionProduct(models.Model):    
    start_date = models.D         


        
相关标签:
1条回答
  • 2021-01-20 04:53

    I ended up writing a custom Func expression that does exacly what I was looking for. This is very Postgresql specific and a bit hacky but it works, even when used in more complex queries than the one illustrated above.

    class DateAdd(Func):
        """
        Custom Func expression to add date and int fields as day addition
        Usage: SubscriptionProduct.objects.annotate(end_date=DateAdd('start_date','duration')).filter(end_date__gt=datetime.now)
        """
        arg_joiner = " + CAST("
        template = "%(expressions)s || ' days' as INTERVAL)"
        output_field = DateTimeField()
    

    Note that I had to do the arg_joiner trick in order for both field names to be resolved properly when used in subselect expressions

    0 讨论(0)
提交回复
热议问题