how to tell if a screen is add or change in django admin

I am trying to determine if the admin screen in Django is add or change in the save method. If I internet search on this, I cannot find any answer. What is the proper way to do this in Python?


Solution 1:

An object has a primary key that is not None in case you update the model, so you can check this, for example with:

class MyModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        if obj.pk is None:
            # add
            pass
        else:
            # change
        super().save_model(request, obj, form, change)

Solution 2:

As with ModelForms, you can use a similar trick:

def save_model(self, request, obj, form, change):
    if obj._state.adding:
        # Adding
    else:
        # Editing

    super().save_model(request, obj, form, change)