Home > Back-end >  How to update multiple objects in django
How to update multiple objects in django

Time:11-09

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!

CodePudding user response:

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')

CodePudding user response:

at:

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()

should filter by the field and then loop through each

on_going_issues = MaintenanceIssue.objects.filter(issue_status='On Going')
for one in on_going_issues:
   if one.pending_issue > 6:
       one.issue_status = "Pending"
       one.save()

CodePudding user response:

you can do it with one line and it will be much faster

MaintenanceIssue.objects.filter(issue_status='On Going').update(issue_status = "Pending")
  • Related