Y
Y
YuriyCherniy2020-06-26 23:56:01
Django
YuriyCherniy, 2020-06-26 23:56:01

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 IntegrityErrorno 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

3 answer(s)
_
_, 2020-06-27
@YuriyCherniy

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

Or look awayget_or_create

D
Dr. Bacon, 2020-06-27
@bacon

Send UserProfile creation to a signal when creating a user

D
Dmitry, 2020-06-27
@pyHammer

@register.simple_tag
def get_brand():
    '''
    set brand name instead of 'Главная' in the navbar
    '''
    user_profile, _ = UserProfile.objects.get_or_create(user_id=1)
    return user_profile.brand

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question