0
我在移植現有的數據庫應用程序的Django(好多了!),並創造了Django模型如下:Django:刪除M2M孤兒條目?
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嗎?
精美的作品,謝謝! – AP257 2010-12-07 22:16:16