I have such a model

class Report(models.Model): user = models.ForeignKey(Profile, related_name='user_report') department = models.ForeignKey(Department, related_name='report') created_date = models.DateTimeField(default=timezone.now()) edited_by = models.ForeignKey(User) edited_at = models.DateTimeField(default=timezone.now()) 

so I need to filter this model by week, that is, as a result, I should have it, the first week of the year, so much Report, the second week, so many, etc. I can of course do it manually, but it will not work so nicely I want instead, I did this DB.

  • I tried it for months at a time I got truncate_date = connection.ops.date_trunc_sql ('month,' created_date ') object_date = Profile.objects.extra ({' date ': truncate_date}) report = object_date.values ​​(' date ',' user_report__stat_report__name '). filter (id = profiles_id) .annotate (Sum (' user_report__stat_report__value ')). order_by (' date ') - ilgiz kasymov
  • I would just start another week field in the model - andreymal

1 answer 1

Django ORM can not be grouped by week. It is easy to calculate grouping by day:

 from django.db.models import Count Report.objects.values('created_date').annotate(Count('id')) 

Weekly, either programmatically or SQL queries without ORM, if the DBMS supports it. Type of such:

 SELECT WEEK('created_date') AS 'week', COUNT(*) AS 'count' FROM appname_report GROUP BY week ORDER BY week 
  • That's exactly what I tried, and there is no such thing there either by SQL query! and manually do something not very nice! - ilgiz kasymov
  • Kakub DBMS do you use? - Sergey Gornostaev
  • Database Mysql - ilgiz kasymov
  • one
    How not? There is SELECT WEEK('created_date') AS 'week', COUNT(*) AS 'count' FROM appname_report GROUP BY week ORDER BY week - Sergey Gornostaev
  • Thank you very much for the rescue) - ilgiz kasymov