1

I have the following list, containing the weeks in the year (python - Django):

weeks = list(range(1,53))

I have a Project model with date_started and date_registered attributes as follows:

class Project(models.Model):
    from_company = models.ForeignKey(Company,on_delete=models.CASCADE)
    project_name = models.CharField("Nombre de Proyecto", max_length=200,unique=True)
    follow_date = models.DateField("Fecha de Seguimiento", default=timezone.now() + timezone.timedelta(days=5))
    date_registered = models.DateTimeField("Fecha de Registro",auto_now_add=True)
    date_started = models.DateTimeField("Fecha de Inicio",null=True)
    last_modified = models.DateTimeField("Ultima Vez Modificado",auto_now=True)

Currently, I'm itterating through each week and get the lenght of the queryset that matches the date_registered__week with the week in the loop, and appending it to a list, like so:

project_active_week = []
for week in weeks:
            if week is not None:
                active_projects = [x.project_name for x in Project.objects.filter(date_registered__week = week,date_registered__year = timezone.now().year)]
                project_active_week.append(len(active_projects))

I have several of this stuff going on and my app has become very slow. Is there a way to perform this more efficiently? Database is Sqlite.

Thank you very much for your help!

  • You may already be aware, but just for sake of completeness and clarity of the question I'll state, the reason why your implementation is slow is because you are iterating over a queryset within the loop body, which gets executed 52 times, thus you are executing 52 separate database queries. [When querysets are evaluated](https://docs.djangoproject.com/en/3.0/ref/models/querysets/#when-querysets-are-evaluated) – Hymns For Disco Feb 08 '20 at 03:18
  • Does this answer your question? [How to execute a GROUP BY ... COUNT or SUM in Django ORM?](https://stackoverflow.com/questions/45547674/how-to-execute-a-group-by-count-or-sum-in-django-orm) – Hymns For Disco Feb 08 '20 at 03:29

0 Answers0