Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
todorvelichkov opened this issue Jul 16, 2024 · 2 comments
Open

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

todorvelichkov opened this issue Jul 16, 2024 · 2 comments

Comments

@todorvelichkov
Copy link

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
Copy link
Collaborator

auvipy commented Sep 7, 2024

would you mind coming with a working solution as PR?

@todorvelichkov
Copy link
Author

@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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants