Home > Software engineering >  Update only that property not all model, django
Update only that property not all model, django

Time:11-06

@property
def policy_escape(self):
    if self.date - datetime.date.today:
        self.status = 2
        self.save()

def save(self, *args, **kwargs):
   self.counter = counter   1

I have this logic for policies. For every policy created I want to increase a property nnumber(this is not exact my case).

I want when policy date is today date to change the status of that policy. But when I change it, the policy counter is increasing.

Can someone help me to update only status without updating other properties?

Thanks in advance

CodePudding user response:

You could limit the update_fields:

@property
def policy_escape(self):
    if self.date - datetime.date.today:
        self.status = 2
        self.save(update_fields=("status",))

However, the particular Python object would still have the changed counter. So you would have to avoid any other save calls on that object.

You could instead pass a custom kwarg:

@property
def policy_escape(self):
    if self.date - datetime.date.today:
        self.status = 2
        self.save(update_counter=False)

def save(self, *args, **kwargs, update_counter=True):
    if update_counter:
        self.counter  = 1
    # ...
    super().save(*args, **kwargs):

Another way to avoid save being called at all is using Queryset.update instead:

@property
def policy_escape(self):
    if self.date - datetime.date.today:
        self.__class__.objects.filter(pk=self.pk).update(status=2)
        # self.status = 2  # if the current object should reflect that change
  • Related