how to access manager from a model instance?

93 views
Skip to first unread message

felix

unread,
Mar 25, 2015, 3:18:25 PM3/25/15
to django...@googlegroups.com
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?

Felix.

Anderson Resende

unread,
Mar 26, 2015, 10:48:22 AM3/26/15
to django...@googlegroups.com
Can you give a example? be more especific, post some code.

Erik Cederstrand

unread,
Mar 26, 2015, 11:20:03 AM3/26/15
to Django Users

> Den 25/03/2015 kl. 20.20 skrev felix <fe...@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.


Erik

felix

unread,
Mar 26, 2015, 12:12:49 PM3/26/15
to django...@googlegroups.com
El 26/03/15 11:19, Erik Cederstrand escribió:
Thanks Erik for your suggestions and Anderson for responding to my request.

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)
        ....


Reply all
Reply to author
Forward
0 new messages