0

Good evening,

I would like to ask, if there's a different method to a raw sql query to update items by a certain condition inside my views.py? For example, I know I could do an insert query like this:

models.py

class Person(models.Model):
    name = models.CharField()
    age = models.IntegerField()
    value = models.IntegerField()

views.py

def something(request):
    ...
    qs = Person(name="John Doe", age=34, value=10)
    qs.save()
    ...

Is there a similiar method for updating all "Persons" if they fit a certain condition?

...
qs = Person("UPDATE Person SET value=5 WHERE age < 30") # or something like this
qs.save()
...

Thanks for all your help and advice and a great weekend to all of you!

1
  • Person.objects.filter(age__lt=30).update(value=5) Commented Dec 18, 2020 at 20:56

1 Answer 1

1

You can make use of .update(…) [Django-doc] to update records of the corresponding table, and use .filter(…) [Django-doc] to specify what items to update.

You thus can filter with:

Person.objects.filter(age__lt=30).update(value=5)

Here we make use of the __lt lookup [Django-doc] to specify that the age should be less than 30.

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.