Count number of records by date in Django

后端 未结 5 991
失恋的感觉
失恋的感觉 2020-11-28 23:49

I have a model similar to the following:

class Review(models.Model):
    venue = models.ForeignKey(Venue, db_index=True)
    review = models.TextField()  
           


        
5条回答
  •  萌比男神i
    2020-11-29 00:30

    Also you can define custom function:

    from django.db.models.expressions import Func
    
    # create custom sql function
    class ExtractDateFunction(Func):
        function = "DATE" # thats the name of function, the way it mapped to sql
    
    # pass this function to annotate
    Review.objects.filter(venue__pk=2)
          .annotate(date_created=ExtractDateFunction("datetime_created"))
          .values('date_created')
          .annotate(created_count=Count('id'))
    

    Just make sure that your DB engine supports DATE function

提交回复
热议问题