Django:删除 M2M 孤立条目?

发布于 2024-10-06 12:06:44 字数 880 浏览 0 评论 0原文

我将现有的数据库应用程序移植到 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)

我已从现有数据填充了模型。问题是数据非常混乱,并且存在孤立的 AuthorSubject 条目,没有相关的 Book 条目。

有没有一种好方法可以使用 Django 删除这些 AuthorSubject 条目?像这样的东西 - 但这不起作用...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぃ双果 2024-10-13 12:06:45

根据您的模型,类似的方法可能会起作用:

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

我没有对此进行测试,但希望它能给您一个想法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文