django request for OBD



  • We need to make the following request for OBD:

       SELECT s.id,count(s.id) FROM staff AS s
       JOIN tasks AS t ON t.author_id = s.id
       WHERE status_id IN(1,2) AND date_creation > '2015-01-01'
       GROUP BY s.id;
    

    How do we do this through the django models?



  • If models look like this:

    class Staff(models.Model):
        # ...
    

    class Task(models.Model):
    staff = models.ForeignKey(Staff)
    status = models.ForeignKey(Status)
    date_creation = models.DateField()

    Then:

    import datetime
    from django.db.models import Count

    Staff.objects.filter(
    task__status_id__in=[1, 2],
    task__date_creation__gt=datetime.date(2015, 1, 1)
    ).values('id').annotate(Count('id')) # или annotate(num_tasks=Count('id'))




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2