Django:删除M2M孤儿条目? [英] Django: delete M2M orphan entries?
本文介绍了Django:删除M2M孤儿条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Book(models.Model):
title = models.CharField(max_length = 200)
author = models.ForeignKey(作者)
subject = models.ManyToManyField(Subject,related_name ='subject')
class作者(models.Model):
name = models.CharField(max_length = 200)
class Subject(models.Model):
name = models .CharField(max_length = 200)
我已经从现有数据填充了模型。问题是数据是相当凌乱的,有孤儿作者
和主题
条目,没有相关的书
。
有没有一个很好的方法我可以使用Django删除这些作者
和主题
条目?这样的东西,但这不行。
orphan_authors = Author.objects.filter(book_set = None)
for orphan_authors:
orphan.delete()
orphan_subjects = Subject.objects.filter(book_set = None)
for orphan_subjects中的孤儿:
orphan.delete( )
还是应该使用原始SQL?
解决方案
根据你的模型,这样的事情可能会起作用:
authors = Author .objects.all()
for a作者:
books = Book.objects.filter(author = a)
如果不是书籍:
a.delete()
我没有测试这个,但希望能给你一个想法。
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?
解决方案
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.
这篇关于Django:删除M2M孤儿条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文