Opened 10 years ago

Closed 10 years ago

#7368 closed (worksforme)

Problem when overriding '__init__' / 'save' methods (models.model)

Reported by: Eric Owned by: nobody
Component: Core (Other) Version: master
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


In this sample model :

import logging

class Test(models.Model):
    title = models.CharField(max_length = 50)

    def __init__(self, *args, **kwargs):
        super(Test, self).__init__(*args, **kwargs)
        self.title = 'a_' + self.title
        logging.debug ('in_init : %s' % self.title)

    def save(self):
        logging.debug ('in_save : %s' % self.title)
        self.title = self.title[2:]
        logging.debug ('in_save2 : %s' % self.title)
        return super(Test, self).save()
    def __unicode__(self):
        return self.title
    class Admin:

The save fonction was called twice and so, the field 'title' does not contains the value without the 2 first characters 'a_' where add init.

Try this :

Add a 'test' row with title : 'This is a test'; saved; the list show 'a_This is a test', this is right at this moment. Edit it and without changing anything, hit 'Save and edit' button. 'a_' is append at the beginning of the title each time row was saved. Same problem with signals 'pre_save'.

If I try with she shell ' shell', no problems.

Change History (2)

comment:1 Changed 10 years ago by Eric

Summary: Save in models was called twiceProblem when overriding '__init__' / 'save' methods (models.model)

Sorry, it was late when I posted the message. After verification, I try to reformulate.

In fact, if during the initialization I added 'a_' to a field and when recording I delete 'a_', they are not deleted.

It seems to me that when recording (method save), a new object is instantiated and that 'a_' is added once again and SQL uses these values to perform the 'update' query without firing the method 'save'.

comment:2 Changed 10 years ago by sebastian.hillig

Resolution: worksforme
Status: newclosed

Having tested your example I couldn't encounter any problems running the current svn version (8255).

Note: See TracTickets for help on using tickets.
Back to Top