Does Django save model objects other than `save()` or `create()` methods?

Question:

I’m writing something like the following:

class Foo(models.Model):
    a = models.CharField()

def f(foo: Foo) -> Foo:
    y = Foo(
        **{field.name: getattr(foo, field.name) for field in foo._meta.get_fields()}
    )  # copy foo with pk
    y.a = "c"
    return y

My concern is whether y are saved to DB before users call save() method. Could it occur?

Asked By: tamuhey

||

Answers:

It’s not saved. You need to actually call y.save() for the updated fields to be persisted to the DB.

In this case, you can make the save more efficient by specifying fields which actually changed:

y.save(update_fields=['a'])
Answered By: smac89

No, y instance won’t be saved to DB before users call save() method. If you want to save the new instance y to the database, you need to call y.save().

Answered By: August Infotech
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.