简体   繁体   English

使用 GenericForeignKey 级联删除模型而不使用 GenericRelation

[英]Cascade delete of model with GenericForeignKey without using GenericRelation

I'm creating a reusable django app which includes a model with GenericForeignKey which I need to be cascade deleted.我正在创建一个可重用的 django 应用程序,其中包含一个带有GenericForeignKey的模型,我需要将其级联删除。

This model may be attached to any other.该模型可以连接到任何其他模型。 I have no control over target model class as it is outside of the app.我无法控制目标模型类,因为它在应用程序之外。 This means I can not add GenericRelation field to it and can't force user to add it as target might be in another third-party app.这意味着我不能向它添加GenericRelation字段,也不能强制用户将它添加为目标可能在另一个第三方应用程序中。

Assuming we have such models (having NO control over Post and PostGroup ):假设我们有这样的模型(无法控制PostPostGroup ):

class Tag(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    object = GenericForeignKey()

class PostGroup(models.Model):
    title = models.CharField(max_length=255)

class Post(models.Model):
    title = models.CharField(max_length=255)
    group = models.ForeignKey(PostGroup, on_delete=models.CASCADE)

Is there a way to delete Tag in case of PostGroup queryset is being deleted?如果PostGroup被删除,有没有办法删除Tag

Eg not only post_group.delete() but also PostGroup.objects.delete() .例如不仅是post_group.delete() ,还有PostGroup.objects.delete()

You can use pre_delete signal to achieve this:您可以使用pre_delete信号来实现这一点:

from django.db.models.signals import pre_delete
from django.dispatch import receiver


@receiver(pre_delete) # add relevant sender to signal (not mandatory)
def post_group_deleted(sender, instance, using, **kwargs):
    # Query tags with the instance of PostGroup and delete them
    if isinstance(instance, Tag):
        return

    Tag.objects.filter(
        content_type=ContentType.objects.get_for_model(instance),
        object_id=instance.pk
    ).delete()

See documentationhere请参阅此处的文档

Unlike ForeignKey, GenericForeignKey does not accept an on_delete argument to customize this behavior;与 ForeignKey 不同,GenericForeignKey 不接受 on_delete 参数来自定义此行为; if desired, you can avoid the cascade-deletion by not using GenericRelation, and alternate behavior can be provided via the pre_delete signal.如果需要,您可以通过不使用 GenericRelation 来避免级联删除,并且可以通过 pre_delete 信号提供替代行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM