Answer the question
In order to leave comments, you need to log in
Is it appropriate to guarantee transaction atomicity in my case?
I wrote a tag that takes data from the super user profile and transfers it to the template. But when you first open the page of the site, Django swears that the super user does not have a profile. In order not to go into the admin panel or go to create a profile, I added the try / finally construction. Does it make sense in such a simple case to guarantee atomicity transaction.atomic()
if IntegrityError
no manipulations have been performed with the database before?
@register.simple_tag
def get_brand():
'''
set brand name instead of 'Главная' in the navbar
'''
try:
with transaction.atomic():
UserProfile.objects.create(user_id=1)
finally:
return UserProfile.objects.first().brand
Answer the question
In order to leave comments, you need to log in
No, it makes no sense to wrap one operation in a transaction.
But I would rewrite your code like this:
@register.simple_tag
def get_brand():
'''
set brand name instead of 'Главная' in the navbar
'''
try:
user_profile = UserProfile.objects.get(user_id=1)
except UserProfile.DoesNotExist:
user_profile = UserProfile.objects.create(user_id=1)
return user_profile.brand
get_or_create
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question