How to show related items using DeleteView in Django?

后端 未结 2 1418
我在风中等你
我在风中等你 2020-11-29 05:03

I am doing a view to delete (using the generic view DeleteView from Django) an instance from a model, but it cascades and deletes instances from other models:



        
2条回答
  •  离开以前
    2020-11-29 05:45

    You can use the Collector class Django uses to determine what objects to delete in the cascade. Instantiate it and then call collect on it passing the objects you intend to delete. It expects a list or queryset, so if you only have one object, just put in inside a list:

    from django.db.models.deletion import Collector
    
    collector = Collector(using='default') # or specific database
    collector.collect([some_instance])
    for model, instance in collector.instances_with_model():
        # do something
    

    instances_with_model returns a generator, so you can only use it within the context of a loop. If you'd prefer an actual data structure that you can manipulate, the admin contrib package has a Collector subclass called NestedObjects, that works the same way, but has a nested method that returns a hierarchical list:

    from django.contrib.admin.utils import NestedObjects
    
    collector = NestedObjects(using='default') # or specific database
    collector.collect([some_instance])
    to_delete = collector.nested()
    

    Updated: Since Django 1.9, django.contrib.admin.util was renamed to django.contrib.admin.utils

提交回复
热议问题