brad
brad

Reputation: 501

django changing the db

i'm writing an app with django and i need to change a specific model when

ever it been saved. i.e lets say i have a model A and a client want to save

changes to that model - i need to also save a change (only if the client

changed a certain field) to the same model (not instance).

my code:

@receiver(pre_save, sender=A)
def my_callable(sender, instance, **kwargs):
    a = A.objects.filter(b=True).all()
    for my_a in a:
        my_a.b= False
        my_a.save()

i have 2 problems with that code:

  1. it has an infinite recursion
  2. i don't know how to check which field had changed

and ideas?

Upvotes: 0

Views: 58

Answers (2)

skolsuper
skolsuper

Reputation: 639

Use .update(b=False) on the queryset:

@receiver(pre_save, sender=A)
def my_callable(sender, instance, **kwargs):
    A.objects.filter(b=True).update(b=False)

The update is done in SQL, doesn't call model's save() method or trigger any signals

.update() docs

Upvotes: 1

skolsuper
skolsuper

Reputation: 639

Assuming you're able to use Django1.8, this exact use case is covered in the docs actually: https://docs.djangoproject.com/en/1.8/ref/models/instances/#customizing-model-loading

Cliff notes: use the from_db method to customize loading of the model and save a copy of the instance's attributes as it is loaded, and then compare them before it is saved.

If you want to compare form data to a model instance to see if a user is changing it, do that in the view, not with a signal.

Upvotes: 0

Related Questions