Aman Sharma
Aman Sharma

Reputation: 93

Django save a change to Database

I'm trying to update the is_admin column of the model user_profile. I've written the following code in views.py but it's not updating in the DB. How can I save the change (user_object[0].is_admin = True) to the database?

def post(self, request, format=None):
    users_provided = request.data.get('user_ids')
    for each_user in users_provided:
        user_object = UserProfile.objects.filter(user__is_active=True, user_id=each_user)
        if (user_object.exists()):
            user_object[0].is_admin = True
            user_object.update()

Upvotes: 3

Views: 482

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can update the item with:

def post(self, request, format=None):
    users_provided = request.data.get('user_ids')
    for each_user in users_provided:
        user_object = UserProfile.objects.filter(user__is_active=True, user_id=each_user)
        user_item = user_object.first()
        if user_item:
            user_item.is_admin = True
            user_item.save()

We can boost the efficiency significantly by writing this as:

def post(self, request, format=None):
    users_provided = request.data.get('user_ids')
    UserProfile.objects.filter(
        user__is_active=True,
        user_id__in=users_provided
    ).update(is_admin=True)

Upvotes: 3

Amin
Amin

Reputation: 2853

Use user_object[0].save():

if (user_object.exists()):
    user_object[0].is_admin = True
    user_object[0].save()

Upvotes: 1

Related Questions