Django: delete M2M orphan entries?
I'm porting an existing database application over to Django (so much better!), and have created 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've populated the models from existing data. The problem is that the data is pretty messy, and there are orphan Author
and Subject
entries, with no related Book
.
Is there a nice way I could use Django to delete these Author
and Subject
entries? Something like this - but this doesn't work...
开发者_JAVA百科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?
Based on your model, something like this may work:
authors = Author.objects.all()
for a in authors:
books = Book.objects.filter(author=a)
if not books:
a.delete()
I didn't test this, but hopefully it gives you an idea.
精彩评论