Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update multiple objects in django

Tags:

python

orm

django

I'd like to update more than one objects at same time, when the register date achieve more than 6 days:

The Idea is update all issue_status from 'On Going' to 'Pending' for each objects

Is it necessary iterate it?

Below is my current code and error:

models.py
class MaintenanceIssue(models.Model):   
    issue_status = models.CharField(max_length=30, choices=[('pending', 'Pending'), ('on going', 
    'On going'), ('done', 'Done')])    
    register_dt = models.DateTimeField(blank=True, null=True) 

    @property
    def pending_issue(self):
        issue_time_diff = (datetime.now() - self.register_dt).days
        return issue_time_diff

views.py:

on_going_issues = MaintenanceIssue.objects.get(issue_status='On Going')
    if on_going_issues.pending_issue > 6:
        on_going_issues.issue_status = 'Pending'
        on_going_issues.save()

get() returned more than one MaintenanceIssue -- it returned 61!

like image 410
HudsonBarroso Avatar asked Oct 18 '25 10:10

HudsonBarroso


1 Answers

To update all objects in one go, you'll need to create a query that selects all objects you want to update then call update on it

MaintenanceIssue.objects.filter(
    issue_status='On Going',
    register_dt__lt=datetime.datetime.now() - datetime.timedelta(days=6)
).update(issue_status='Pending')

That filter does not exactly match your property, the following should get you a better match although it's a bit uglier

from django.db.models import F, Value
from django.db.models.functions import ExtractDay

MaintenanceIssue.objects.filter(
    issue_status='On Going'
).annotate(
    days=ExtractDay(Value(datetime.datetime.now()) - F('register_dt'))
).filter(
    days__gt=6
).update(issue_status='Pending')
like image 151
Iain Shelvington Avatar answered Oct 20 '25 00:10

Iain Shelvington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!