[Django]-Django save a change to Database

3👍

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)

1👍

Use user_object[0].save():

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

Leave a comment