Answer the question
In order to leave comments, you need to log in
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')
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:
# Цена не изменилась
Answer the question
In order to leave comments, you need to log in
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:
# Цена снизилась
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question