dimagi / django-cte

Common Table Expressions (CTE) for Django
Other
334 stars 46 forks source link

How to use as default manager? #79

Open autoantwort opened 1 year ago

autoantwort commented 1 year ago

I tried to use a CTE as default manager, but I failed to do so:

class PeriodsManager(models.Manager):
    def get_queryset(self):
        # get the end date of the period, oldest period first, newest last
        cte = With(
            QuerySet(MembershipTypePeriods)
            # MembershipTypePeriods.objects
            .order_by('start_date').annotate(
            end_date=Window(
                partition_by=[F('membership_id')],
                expression=Lead('start_date'),
                order_by=F('start_date').asc()
            )
        ))
        return cte.queryset().with_cte(cte)

class MembershipTypePeriods(models.Model):
    objects = PeriodsManager()
    start_date = models.DateField(default=date.today)
    type = models.ForeignKey(MembershipType, on_delete=RESTRICT)
    membership = models.ForeignKey(Membership, on_delete=CASCADE)

Something like

class PeriodsManager(CTEManager):
    def get_queryset(self):
        # get the end date of the period, oldest period first, newest last
        return super().get_queryset().order_by('start_date').annotate(
            end_date=Window(
                partition_by=[F('membership_id')],
                expression=Lead('start_date'),
                order_by=F('start_date').asc()
            )
        )

does not seems to use CTEs

autoantwort commented 1 year ago

Hm If I replace https://github.com/dimagi/django-cte/blob/5c8c1e51faae228fc08ed847a2792347d070a518/django_cte/cte.py#L107C12-L107C12 by qs = CTEQuerySet(cte_query.model) it works