finethen
finethen

Reputation: 433

Python, Django: Alternative to a raw-sql-query

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!

Upvotes: 0

Views: 238

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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.

Upvotes: 1

Related Questions