El 26/03/15 11:19, Erik Cederstrand escribió:
Thanks Erik for your suggestions and Anderson for responding to my request.Den 25/03/2015 kl. 20.20 skrev felix <felix@epepm.cupet.cu>: Yes I know I can't acces the Manager from a model instance, but I need to check the value of a field saved in the database before updating it. Can I do it from the Model clean() method?Depending on your requirements, there's a couple of options. Use refresh_from_db() in up-coming Django 1.8 (https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.refresh_from_db) or the poor man's version: new_obj = MyModel.objects.get(pk=obj.pk) Remember to audit your use of transactions. If you always want to update a value, e.g. increment a counter, you can use an F() expression: https://docs.djangoproject.com/en/1.7/ref/models/queries/#f-expressions If none of these are appropriate, you need to describe your requirements in more detail.
I finally left my model this way, accordingly to what you called the poor man's version ;) :
class InvoiceDetail(models.Model):
....
def clean(self):
.....
if self.pk:
old_element = InvoiceDetail.objects.get(id=self.pk)
....
No comments:
Post a Comment