Anupam
Anupam

Reputation: 15620

django update_or_create(), see what got updated

My django app uses update_or_create() to update a bunch of records. In some cases, updates are really few within a ton of records, and it would be nice to know what got updated within those records. Is it possible to know what got updated (i.e fields whose values got changed)? If not, does any one has ideas of workarounds to achieve that?

This will be invoked from the shell, so ideally it would be nice to be prompted for confirmation just before a value is being changed within update_or_create(), but if not that, knowing what got changed will also help.

Update (more context): Thought I'd give more context here. The data in this Django app gets updated through various means (through users coming on the web site, through the admin page, through scripts (run from the shell) that populate data from a csv etc.). The above question is important mostly for the shell scripts that update data from csvs, hence a solution at the database/trigger/signal level may not be helpful here (I guess).

Upvotes: 3

Views: 2534

Answers (2)

Anupam
Anupam

Reputation: 15620

This is what I ended up doing:

for row in reader:
    school_obj0, created = Org.objects.get_or_create(school_id = row[0])

    if (school_obj0.name != row[1]):
        print (school_obj0.name, '==>', row[1])
        confirmation = input('proceed? [y/n]: ')
        if (confirmation == 'y'):
                school_obj1, created = Org.objects.update_or_create(
                                school_id = row[0], defaults={"name": row[1],})

Happy to know about improvements to this approach (please see the update in the question with more context)

Upvotes: 1

e4c5
e4c5

Reputation: 53744

This will be invoked from the shell, so ideally it would be nice to be prompted for confirmation just before a value is being changed

Unfortunately, databases don't work like that. It's the responsibility of applications to provide this functionality. And django isn't an application. You can however use django to write an application that provides this functionality.

As for finding out whether an object was updated or created, that's what the return value gives you. A tuple where the second value is a flag for update or create

Upvotes: 0

Related Questions