X
X
xenofobius2017-07-07 17:27:45
Django
xenofobius, 2017-07-07 17:27:45

How to update only changed fields in django?

There is a form, the fields are optional, upon receipt on the server, I check whether there is a record with such an id or not, if it exists, I pass initial and the current form, then I check change_data and supplement the existing model using them (if the fields != '' or None) .

try:
                current_user = Passport.objects.get(id=current_id)
                f = PassportForm(request.POST, request.FILES, initial=model_to_dict(current_user))

                if f.has_changed():

                    for i in f.changed_data:
                        if (f.data[i] != '') and (f.data[i] != None):
                            current_user.i = f.data[i]
                            current_user.__setattr__(i, f.data[i])

                    current_user.save()

The method seems a little crutch to me, the more the problem arises when a file is transferred and it needs to be updated, is it possible to somehow implement this using django?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Gasoid, 2017-07-07
@ksenofobius

save(update_fields=['field'])

D
Dimonchik, 2017-07-07
@dimonchik2013

https://docs.djangoproject.com/en/1.11/ref/models/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question