Search code examples
python-3.xdjangodjango-modelsdjango-rest-frameworkdjango-filter

How to delete upto n type of data in self forienkey using django rest framework?


class Directory(models.Model):
    name = models.CharField(max_length=100)
    parent_directory= models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True)

I want to delete root folder and all the folders which is inside the root folder (root folder means parent_directory is null in Directory model), https://i.sstatic.net/oszCR.png, In this picture root is base directory and rest of the all folders are inside the root folder and if i delete the root folder then all the folders which is inside the root folder needs to be deleted ]

for exam:

  1. root is parent_directory
  2. test sub3 and sub4 is inside root directory base on table photo
  3. Bhavya is inside sub4 based on photo
  4. top is inside in Bhavya

Now if I want to delete object number 22 means root directory then 26, 29, 33 and 34 should also be deleted.


Would you please let me know how can delete this n type of object without on_delete=models.CASCADE ?


Solution

  • You can make an iterate script that will collect all the items to remove. This will make 𝓞(d) queries with d the depth of the subtree, so:

    from operator import attrgetter
    
    
    def delete_with_descendants(*directories):
        next_gen = directories = set(directories)
        while next_gen:
            next_gen = Directory.objects.filter(parent_directory__in=next_gen)
            directories.update(next_gen)
        # directories is a set of Directory objects that you can process
        # …
        # remove the directories
        Directory.objects.filter(pk__in=map(attrgetter('pk'), directories)).delete()

    So you can then delete the directory including all the descendants with delete_with_descendants(my_directory).