Django:删除 M2M 孤立条目?
我将现有的数据库应用程序移植到 Django(好多了!),并创建了 Django 模型,如下所示:
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)
我已从现有数据填充了模型。问题是数据非常混乱,并且存在孤立的 Author
和 Subject
条目,没有相关的 Book
条目。
有没有一种好方法可以使用 Django 删除这些 Author
和 Subject
条目?像这样的东西 - 但这不起作用...
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()
或者我应该使用原始 SQL?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的模型,类似的方法可能会起作用:
我没有对此进行测试,但希望它能给您一个想法。
Based on your model, something like this may work:
I didn't test this, but hopefully it gives you an idea.