Django admin内联计算字段不会保存(Django admin inline calculated field won't save)

编程入门 行业动态 更新时间:2024-10-26 12:28:32
Django admin内联计算字段不会保存(Django admin inline calculated field won't save)

我的内联中的一个字段需要计算。 我覆盖了BaseInLineFormSet的clean方法并且可以在那里进行计算并显然在那里设置了字段的值,但它没有保存到DB中,因此也没有显示。 该字段默认为零,顺便说一下,如果重要的话。 这是一个硬编码版本:

class EmployeeAssignmentInLineFormSet(BaseInlineFormSet): def clean(self): super(EmployeeAssignmentInLineFormSet, self).clean() self.cleaned_data[0]['cost'] = 5000

我也尝试在ModelAdmin中覆盖save_formset - 结果相同:

def save_formset(self, request, form, formset, change): formset.cleaned_data[0]['cost'] = 5000 formset.save()

当我将值设置为clean时,我可以看到它在设置为save_formset时被设置,但它仍然在DB中结束为零。 我在错误的地方还是什么?

One of the fields in my inline needs to be calculated. I overrode the BaseInLineFormSet clean method and can do the calculation there and apparently set the field's value there but it doesn't get saved to the DB, and consequently is also not displayed. The field defaults to zero, btw, in case that matters. Here's a hard-coded version:

class EmployeeAssignmentInLineFormSet(BaseInlineFormSet): def clean(self): super(EmployeeAssignmentInLineFormSet, self).clean() self.cleaned_data[0]['cost'] = 5000

I also tried overriding save_formset in the ModelAdmin - same result:

def save_formset(self, request, form, formset, change): formset.cleaned_data[0]['cost'] = 5000 formset.save()

When I set the value just in clean I can see it's been set when it gets to save_formset, but it still ends up being zero in the DB. Am I in the wrong place or what?

最满意答案

我不认为ModelFormSet有像这样的cleaning_data属性 https://github.com/django/django/blob/master/django/forms/models.py#L623

在这种情况下,我不确定为什么你没有从上面的代码中获得异常,但在我看来你应该尝试:

def clean(self): super(EmployeeAssignmentInLineFormSet, self).clean() self.forms[0].cleaned_data['cost'] = 5000

Doesn't seem to be much interest in this but for the sake of completeness, this is what I ended up doing. All my gazillion attempts at trying to save the field when the record is saved failed. Simply putting something into cleaned_data doesn't work. I tried overriding clean, save_model, save_related, save_formset - no joy. So now I'm in the Inline options:

readonly_fields = ('get_cost', ) fields = ('project', 'start_date', 'end_date', 'effort', 'role', 'get_cost') def get_cost(self, obj): if obj.effort and obj.cost == 0.0: obj.cost = obj.employee._calculate_cost(obj.effort) obj.save() return obj.cost get_cost.short_description = 'Cost'

Need the conditional of course to avoid saving the cost every time the inline formset is loaded. Seems odd to save the field after the rest of the record has been saved, but it works.

更多推荐

本文发布于:2023-08-06 18:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内联   字段   admin   Django   save

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!