Django:更新X模型数量的表单 [英] Django: form that updates X amount of models

查看:117
本文介绍了Django:更新X模型数量的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,它显示一个过滤的模型实例列表,并允许用户更新其中的一些字段或添加新的字段作为一个表单。



我很好奇什么是一个聪明的方法,删除和重新保存所有的输入数据或比较每个数据和保存已编辑/新的字段&实体。



我想介绍一下,我使用postgres保存这些值,我显示这个表单的大约20个条目。

解决方案

QuerySet对象具有update()方法 - 它在ie中使用。管理面板从更改列表批量更新多个选定对象。以下是 django's的方法参考官方文档



如何使用它:



只需使用所需的模型创建查询更新(昵称MyModel的字段名为'my_field'):

  qs = MyModel.objects.all()
qs.update(my_field = value)

就是这样 - 记住update()方法不会发送任何像save()方法的信号 - 它将直接运行查询到数据库。



至于'通过表单添加字段' - 我不知道我是否对的?你想添加附加的相关模型或动态地添加到数据库模型表中的字段?



如果要添加相关模型,请使用InlineFormset( http://docs.djangoproject.com/en/dev/topics/forms/modelforms /#inline-form ) - 它很容易处理。
否则,您必须按照如下所述向模型_meta添加字段:如何动态地将自定义字段添加到模型


I have a page where it displays a filtered model instance list and allows users to update some fields of it or add new fields as a form.

I am curious what wpuld be a clever way of doing this, to delete and resave all the input data or make comparison for each data and save edited / new fields& entities.

I would like to mind you that I use postgres for saving these values and I display around 20 entries for this form.

解决方案

The QuerySet object has the update() method - it's used in ie. Admin Panel for bulk updating multiple selected objects from change lists. Here is the method reference at django's official documentation.

How to use it:

Just create queryset with the models you want to update (assumng that MyModel has field named 'my_field'):

qs = MyModel.objects.all()
qs.update(my_field=value) 

That's it - remember that update() method will not send any signals like the save() method - it will just run query directly to database.

As for 'adding fields via form' - I don't know if I got it right? You want to add additional related models or dynamically add fields to the model table on database?

If you want to add related models then use InlineFormset (http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-form) - it's quite easy to handle. Otherwise you have to add fields to models' _meta as described here: How dynamic add custom field to model.

这篇关于Django:更新X模型数量的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆