1

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

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)

这是一个模型,然后我将如何从模型看起来像这样的土地模型中删除照片。

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.
4

3 回答 3

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)

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

于 2012-11-05T10:35:51.413 回答
1

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

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()

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

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)
于 2012-11-05T10:46:49.240 回答
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().

于 2012-11-05T10:35:29.090 回答