django-activity-stream icon indicating copy to clipboard operation
django-activity-stream copied to clipboard

N+1 queries on queryset.delete()

Open todorvelichkov opened this issue 1 year ago • 2 comments

I just found out that we have a N+1 queries on one of our purge operations. I've traced the problem and found out its caused by #523 which is trying to fix issue #521

IMHO a much better approach to the problem (CASCADE DELETE over GFK) would be to implement a GenericRelation in the model definition. This way Django will do it automatically a much more optimized way with a limited number of queries.

From the docs:

tags = GenericRelation(
    TaggedItem,
    content_type_field="content_type_fk",
    object_id_field="object_primary_key",
)

Note also, that if you delete an object that has a GenericRelation, any objects which have a GenericForeignKey pointing at it will be deleted as well. In the example above, this means that if a Bookmark object were deleted, any TaggedItem objects pointing at it would be deleted at the same time.

Unlike ForeignKey, GenericForeignKey does not accept an on_delete argument to customize this behavior; if desired, you can avoid the cascade-deletion by not using GenericRelation, and alternate behavior can be provided via the pre_delete signal.

todorvelichkov avatar Jul 16 '24 09:07 todorvelichkov

would you mind coming with a working solution as PR?

auvipy avatar Sep 07 '24 12:09 auvipy

@auvipy the GenericRelation field is something that everyone should add into the field definition of the models in their project, it should look like this:

class MyModelName(models.Model):
    # .... field definitions
    follow_set = GenericRelation(
        "actstream.follow",
        content_type_field="content_type_id",
        object_id_field="object_id",
        related_query_name="mymodelname",
    )

So in terms of changes, what's necessary is probably the ability to disable the current delete functionality and add documentation for how to handle this with GenericRelations (i.e. the example above).

todorvelichkov avatar Sep 11 '24 07:09 todorvelichkov