0

I have a Comment model that needs the admin approval. I am providing a view for the admin to do that.

However, I am using an expensive way to update the approval status.

comments = # a list that contain Comment objects

for c in comments:
    c.approved = True
    c.approved_on = #now
    c.save()

As you can see I am looping over all the objects in the list and every time I am hitting the database.

I am looking for a way that makes me do something similar to this in SQL

UPDATE comments SET approved = 1 WHERE id IN(...........)

This will do the same thing in one SQL query.

Is there any way to do this in Django?

like this with using an approve method in the manager?

Comment.objects.filter(pk__in=[1,2,3]).approve().save()

1 Answer 1

1

The easiest way:

def approve(self):
    return self.get_queryset().update(approved=True)

NOTE: this solution has problem. post_save and pre_save signals will not be called.

If you need this signals, you must iterate items like you do in your example.

def approve(self):
    qs = self.get_queryset()
    for c in qs:  # hit database!
        c.approved = True
        c.approved_on = #now
        c.save()
    return qs
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.