django admin在save_model方法中删除内联对象
我有两个相关的(通过外键关系)模型,并为带有内联的父级创建了管理模型。在某些情况下(通过布尔字段在管理中编辑),我需要删除所有以前的对象(内联)并创建新的对象。我尝试使用 save_model 来实现它,我可以在其中获取所有当前对象的属性并决定是否需要重新创建(内联)对象。 models:
class Model1(models.Model):
reformat = models.BooleanField(default=False)
...
class Model2(models.Model):
model1 = ForeignKey(Model1, related_name='model2')
...
admin:
class Model2Inline(admin.TabularInline):
model = Model2
class Model1Admin(admin.ModelAdmin):
inlines = [Model2Inline]
def save_model(self, request, obj, form, change):
super(Model1Admin, self).save_model(request, obj, form, change)
if obj.reformat:
obj.model2.all().delete()
# creating new objects
...
obj.save()
但是如果我尝试在 model_save 方法中删除这些对象,我会得到 ValidationError。 还有其他可能性来解决这个问题吗?
I have two related (via foreignkey relation) models and created admin model for parent with inlines. In several cases (edited in admin by boolean field), i need to delete all previous objects (inlines) and create new ones. I've tried to make it with save_model, where i can get all current object's properties and decide if i need to recreate (inline) objects.
models:
class Model1(models.Model):
reformat = models.BooleanField(default=False)
...
class Model2(models.Model):
model1 = ForeignKey(Model1, related_name='model2')
...
admin:
class Model2Inline(admin.TabularInline):
model = Model2
class Model1Admin(admin.ModelAdmin):
inlines = [Model2Inline]
def save_model(self, request, obj, form, change):
super(Model1Admin, self).save_model(request, obj, form, change)
if obj.reformat:
obj.model2.all().delete()
# creating new objects
...
obj.save()
But if i try to delete these objects in model_save method i get ValidationError.
Is there other possibilities to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我也遇到了这个问题,经过一两个小时的头撞墙后,通过重写管理对象上的
save_formset()
而不是save_model()< /code> 并在调用超类的
save_formset()
方法后执行所需的操作。这样做意味着保存表单集时您要删除的模型仍然存在,因此您不会收到验证错误。在您给出的示例中,它可能如下所示:
I came across this problem as well, and, after an hour or two of banging my head against the wall, solved it by overriding
save_formset()
on the admin object instead ofsave_model()
and doing the required manipulation after calling the super class'ssave_formset()
method. Doing it this way means the models which you are deleting are still present when the formset is saved, so you don't get the validation error.Here's what it might look like in the example you gave: