Django: delete M2M orphan entries?

我怕爱的太早我们不能终老 提交于 2020-01-06 14:36:01

问题


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...

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?


回答1:


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.



来源:https://stackoverflow.com/questions/4381928/django-delete-m2m-orphan-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!