2010-12-07 108 views
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) 

我填充從現有的數據模型。問題是數據非常混亂,並且有孤兒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嗎?

回答

2

根據您的型號,這樣的事情可能工作:

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

我沒有測試這一點,但希望它給你的想法。

+0

精美的作品,謝謝! – AP257 2010-12-07 22:16:16