Django: delete records for orphans in M2M?

I am migrating an existing database application to Django (much better!) And created the Django models as follows:

class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author) subject = models.ManyToManyField(Subject, related_name='subject') class Author(models.Model): name = models.CharField(max_length=200) class Subject(models.Model): name = models.CharField(max_length=200) 

I populated models from existing data. The problem is that the data is pretty dirty, and there are records of the Author and Subject orphans, without the associated Book .

Is there a good way to use Django to delete these Author and Subject entries? Something like this - but it does not work ...

 orphan_authors = Author.objects.filter(book_set=None) for orphan in orphan_authors: orphan.delete() orphan_subjects = Subject.objects.filter(book_set=None) for orphan in orphan_subjects: orphan.delete() 

Or should I use raw SQL?

0
source share
1 answer

Based on your model, something like this might work:

 authors = Author.objects.all() for a in authors: books = Book.objects.filter(author=a) if not books: a.delete() 

I have not tested this, but hopefully this gives you an idea.

+2
source

Source: https://habr.com/ru/post/1412683/


All Articles