justquick / django-activity-stream

Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.
http://django-activity-stream.rtfd.io/en/latest/
BSD 3-Clause "New" or "Revised" License
2.36k stars 483 forks source link

N+1 queries on queryset.delete() #541

Open todorvelichkov opened 1 month ago

todorvelichkov commented 1 month ago

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.

auvipy commented 20 hours ago

would you mind coming with a working solution as PR?