Reputation: 1129
I have a django app and I need in one view function to get two objects: token
and plan
or create them if they don't exist, here the code I'm currently using:
def get_or_create_token_and_plan(user):
try:
token = Token.objects.get(user=user)
except ObjectDoesNotExist as e:
token = Token.objects.create(user=user)
try:
plan = Plan.objects.get(user=user)
except ObjectDoesNotExist as e:
plan = Plan.objects.create(user=user)
return token, plan
def profile(request):
user = User.objects.get(username=request.user)
token, plan = get_or_create_token_and_plan(user)
context = {'token':token, 'plan':plan}
return render(request, 'profile.html', context)
I'm trying to figure out a way of improving get_or_create_token_and_plan()
function, knowing that token
and plan
objects will be, in theory, created initially at the same time. Except for exceptions, if I merge both try, except
structures into a single one will work, like here:
def get_or_create_token_and_plan(user):
try:
token = Token.objects.get(user=user)
plan = Plan.objects.create(user=user)
except ObjectDoesNotExist as e:
token = Token.objects.create(user=user)
plan = Plan.objects.get(user=user)
return token, plan
The main issue with this is that if token
already exists and plan
doesn't, the I will get an IntegrityError when creating it again for the same user, but as said, in theory this won't happend because both token
and plan
will be created only in this function, so my question is, should I change get_or_create_token_and_plan
in this case or should I use the later example I said.
Upvotes: 0
Views: 130
Reputation: 1089
Django provides a get_or_create function that may be useful to you. So I think you could do.
def get_or_create_token_and_plan(user):
token, _ = Token.objects.get_or_create(user=user)
plan, _ = Plan.objects.get_or_create(user=user)
return token, plan
Upvotes: 1