E
E
Evgeny_A2021-12-27 17:26:18
Django
Evgeny_A, 2021-12-27 17:26:18

How to check if a particular field has changed when saving an instance?

There is this model:

from django.db import models
class Car(models.Model)
    price = models.IntegerField('Price')

When saving an instance of this model, I need to check how the Price field has changed (if it has changed at all). If the price has become more, then do one thing, if less, then do another. Something like this:

from django.db.models.signals import post_save
@receiver(post_save, sender=Car)
def car_is_saved(instance, **kwargs):
    if instance.newprice > instance.price:
        # Цена увеличилась
    elif instance.newprice < instance.price:
        # Цена уменьшилась
    else:
        # Цена не изменилась

Where to get instance.newprice?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny_A, 2021-12-27
@Evgeny_A

I found such a solution, but it creates an additional query to the database. I would like to avoid this, of course.

@receiver(pre_save, sender=Car)
def car_is_saved(sender, instance, **kwargs):
    try:
        obj = sender.objects.get(pk=instance.pk)
    except sender.DoesNotExist:
        pass
    else:
        if obj.price == instance.price:
            # Цена не изменилась
            pass
        elif obj.price < instance.price:
            # Цена поднялась
        elif obj.price > instance.price:
            # Цена снизилась

C
CrewCut, 2015-08-27
@TheMarser

Да, официальный - www.woothemes.com/products/product-vendors
Могу продать, у меня он есть

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question