django-cachalot icon indicating copy to clipboard operation
django-cachalot copied to clipboard

Query which filters on annotation of second query does not have cache invalidated

Open sdolemelipone opened this issue 1 year ago • 1 comments

Hi. This seems like a bug, as I couldn't find anything in the documentation which would explain it. I could create a pull request with a failing test if this does need fixing.

What happened?

The cache for a query was not invalidated, when it should have been. The query contains an annotation and subsequent filter based on querying a ManyToMany field for which the related manager had been modified since the last query.

With models as follows:

class Order(Model):
    ...

class User(AbstractUser, Model):
    orders = ManyToManyField(Order, related_name="users", related_query_name="user")
    ...

and evaluating the queryset returned by the following method:

def all_orders(user): 
    managed = user.orders.all().values_list("pk", flat=True)
    return Order.objects.annotate(
        is_managed=Case(
            When(pk__in=managed, then=True),
                default=False,
                output_field=BooleanField(),
            )
    ).filter(is_managed=True)

>>> user.orders.add(order1)
>>> all_orders(user)
    [<order1>]
>>> user.orders.add(order2)
>>> all_orders(user)
    [<order1>]  # stale!!

What should've happened instead?

The cache for the top level query should have been invalidated:


>>> user.orders.add(order1)
>>> all_orders(user)
    [<order1>]
>>> user.orders.add(order2)
>>> all_orders(user)
    [<order1>, <order2>]  # correct!!

Interestingly the problem does not occur when filtering on the query directly, rather than using an annotation and filtering against that:

def all_orders_good(user):  # correctly re-queries after change to User.orders
    managed = user.orders.all().values_list("pk", flat=True)
    return Order.objects.filter(pk__in=managed)

Steps to reproduce

As above, running on Ubuntu 22.04, Django Version 4.2.5, Python 3.11, Postgres 14.10, Cachalot 2.6.2.

In case you're wondering why I'm filtering in this unusual way, this is a much simpler version of a more complicated all_orders() method which queries some other tables too.

sdolemelipone avatar Feb 23 '24 15:02 sdolemelipone

Also, forcing the evaluation of the "sub" query prevents this problem from occurring:


def all_orders(user): 
    managed = list(user.orders.all().values_list("pk", flat=True))  # force evaluation of query
    ....

sdolemelipone avatar Feb 23 '24 15:02 sdolemelipone