Home > Software design >  Django update_or_create with potentially null idenitfier
Django update_or_create with potentially null idenitfier

Time:06-22

I have a function in Django that accepts a post request. If that post request includes an id, I want to update that object. If the post request sends a blank/null id, I'd like to create a new object and have Django set the ID (primary key) of the model.

Here is what I have:

def save_user_roster_to_db():
name = request.data['name']
id = request.data['id'] # this could be null/blank or be an ID
try:
    user_roster = SavedUserRoster.objects.update_or_create(
        id=id,
        defaults={
            "name": name,
        }
    )
    return user_roster.pk
except:
    raise Exception

However, this seems to try to assign the blank/null value as the ID when creating a new object. How can I tell Django to set its own ID (which is the primary key) if it's creating a new object?

CodePudding user response:

You can't use update_or_create with the id field. Because in the current situation, id can have a value of None, and the Django model can't create the object with an id of None. So I think you can try like the following.

def save_user_roster_to_db():
    name = request.data['name']
    id = request.data['id'] # this could be null/blank or be an ID
    try:
        if id:
            user_roster = SavedUserRoster.objects.get(pk = id).update(name = name)
        else:
            user_roster = SavedUserRoster.objects.create(name = name)
        return user_roster.pk
    except:
        raise Exception

CodePudding user response:

Traditionally id is auto generated and always unique. In this case replacing None id will create exception when you create record for first time.

There are two possible options.

OPTION 1: Create another unique_identified i.e username or email.

def save_user_roster_to_db():
name = request.data['name']
unique_identified = request.data['unique_identified'] # this could be null/blank or be an ID
user_roster, is_created = SavedUserRoster.objects.update_or_create(
        unique_identified=unique_identified,
        defaults={
            "name": name,
        }
    )
return user_roster.pk

OPTION 2:

For Create: Get the last id from database and add 1 with last id, so that It will be the next id value, It will avoid the None exception.

For Update: It will update the existence record against id

def save_user_roster_to_db():
name = request.data['name']
id = request.data['id'] # this could be null/blank or be an ID
if id is None:
   id = int(MyUserModel.objects.all().last().id) 1
user_roster, is_created = SavedUserRoster.objects.update_or_create(
        id=id,
        defaults={
            "name": name,
        }
    )
return user_roster.pk
  • Related