Identify updated field in update or create django

Viewed 102

How do I detect which data has been updated and which has been created in a MyModel.objects.update_or_create() method?

try:
    new_data = MyModel.objects.update_or_create(
        data_1 = active_sheet["{}{}".format("A", row)].value,
        data_2 = active_sheet["{}{}".format("B", row)].value,
    )  
    # default url
    url = reverse('admin:index') + 'some-url/'
    # if some users were only updated, not uploaded
        # pass the updated data to custom template 
        # return the current page with a table of the entries that were not added  
    self.message_user(request, 'Tagged Profile uploaded.')   
    # redirect to selected url
    return HttpResponseRedirect(url)
except Exception as e:
    messages.warning(request, '%s. If you are seing this, there is an error in your file.' % e)
2 Answers

Base on documentation update_or_create returns two values (object, created) and if created is True then it is new object.

The same way works get_or_create()

I got it working with exists().

try:
    if MyModel.objects.filter(
        name = active_sheet["{}{}".format("A", row)].value,
    ).exists():
        # add data to list 
    else: 
        # save the new user into the user model
        MyModel.objects.create(
            name = active_sheet["{}{}".format("A", row)].value,
        )
except Exception as e:
    messages.warning(request, '%s. If you are seing this, there is an error in your file.' % e)
Related