2012-11-07 216 views
0

如何在django中刪除ManyToMany關係。如何將youu刪除M2M然後刪除照片,這是我的模型感謝以下刪除ManyToMany的關係

class Picture(models.Model): 
    owner = models.ForeignKey(User,blank = True) 
    caption = models.CharField(max_length=150, blank=True, null=True) 
    image = ImageField(upload_to='images/',blank = True, null = True) 

class Land(Properies): 
    photo = models.ManyToManyField(Picture,blank=True,related_name='Land_Pictures',null = True) 

我試圖刪除這樣

checked_list = [] 
start = 1    
land_photos = sorted(list(land.photo.select_related()),reverse =True) 
while start < 8: 
    photo = 'photo%s' % start 
    checked = form.cleaned_data[photo] 
    if checked != None: 
     checked_list.append(land_photos[start - 1]) 
     start += 1    
for a_foto in checked_list: 
    land.photo.remove(a_foto) 
    try: 
     a_foto.remove_all_file() 
     a_foto.delete() 
    except OSError: 
     pass 

,然後我得到這樣

Exception Type:  AssertionError 
Exception Value:  
Picture object can't be deleted because its id attribute is set to None. 
錯誤
+0

你是什麼意思與 「刪除」?刪除相關記錄或完全刪除關係? –

+0

如何將youu刪除m2m然後刪除照片這是我的模特以下謝謝 – user1711168

回答

0

Documentation

>>> land.photo.remove(some_picture) 

或周圍的其他方式,使用提供related_name說法:

>>> picture.Land_Pictures.remove(some_land) 

默認情況下,沒有related_name,這將是:

>>> picture.land_set.remove(some_land) 
+0

是的,這將刪除它,但我如何刪除照片它自我我得到一種完整性錯誤的照片和土地被刪除 – user1711168

+0

張貼您的代碼和錯誤然後!我的水晶球壞了 – jpic

+0

這裏是錯誤的圖片對象無法刪除,因爲它的id屬性設置爲None。 – user1711168