Django: form that updates X amount of models

泄露秘密 提交于 2019-12-02 10:23:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3778585/django-form-that-updates-x-amount-of-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!