删除相关模型django

时间:2012-11-05 10:23:02

标签: django django-models

我目前有这个模型如何在不删除公司模型的情况下删除徽标。如果可能,请提供示例代码谢谢。

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 Company(GenericUser):
    company_name = models.CharField(max_length=150,blank = True,null = True)
    logo = models.ForeignKey(Picture,blank = True,null = True)

这是一个模型,然后我将如何从模型看起来像土地模型中移除foto。

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

我一直收到一个错误,比如id设置为none,如果我点击刷新,我认为

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

3 个答案:

答案 0 :(得分:2)

以这种方式更改公司模式:

class Company(GenericUser):
    company_name = models.CharField(max_length=150,blank = True,null = True)
    logo = models.ForeignKey(Picture,blank = True,null = True, on_delete=models.SET_NULL)

docs:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete

答案 1 :(得分:0)

有什么理由:

a)您正在使用(GenericUser)?这无疑会给你带来麻烦。

b)不能只删除属性(如下所示),然后迁移数据?

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 Company(models.Model):
    company_name = models.CharField(max_length=150, blank=True, null=True)
    logo = models.ForeignKey(Picture, blank=True, null=True)

或者您是否尝试删除相关实例: https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove

在这种情况下,您使用remove()

答案 2 :(得分:0)

您必须清除任何公司对象对要删除的图片对象的引用。

logo = company.logo
company.logo = None
logo.delete()

但是,如果多个公司引用了图片,请尝试以下操作:

logo = Picture.object.get(...) # the Picture you want to delete
logo.company_set.update(logo=None)
logo.delete()

您还应该考虑将引用从公司更改为图像,以便默认情况下不会删除相关实例。

class Company(GenericUser):
    company_name = models.CharField(max_length=150,blank = True,null = True)
    logo = models.ForeignKey(Picture,blank = True,null = True, on_delete=models.SET_NULL)