0

I have a Django model:

    @staticmethod
    def getdefault():
        print "getdefault called"
        return cPickle.dumps(set())

    _applies_to = models.TextField(db_index=True, default=getdefault)

For some reason, getdefault() is never called, even as I construct instances of this model and save them to the database. This seems to contradict the Django documentation:

Field.default

The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

Am I doing something wrong?

Update:

Originally, I had this, but then I switched to the above version to debug:

_applies_to = models.TextField(db_index=True, default=cPickle.dumps(set()))

I'm not sure why that wouldn't work.

Update 2: I'm still having difficulty with this. Here is my model:

class Threshold(models.Model):
    # ...
    _applies_to = models.TextField(db_index=True, default=lambda: cPickle.dumps(set()))

And a test:

def setUp(self):
    self.threshold = Threshold() 

    self.threshold.save()

def test_default_applies_to(self):
    self.assertEqual(self.threshold._applies_to, cPickle.dumps(set()))  

This test fails. I'm not sure why.

FAIL: test_default_applies_to (apps.threshold.tests.ThresholdTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 27, in test_default_applies_to
    self.assertEqual(self.threshold._applies_to, cPickle.dumps(set()))
AssertionError: 'N.' != 'c__builtin__\nset\np1\n((ltRp2\n.'

Why might this be happening? Perhaps I don't understand how default is supposed to work.

Nick Heiner
  • 119,074
  • 188
  • 476
  • 699

1 Answers1

1

Remove the staticmethod decorator and it will work :

def getdefault():
    print "getdefault called"
    return cPickle.dumps(set())

_applies_to = models.TextField(db_index=True, default=getdefault)

Edit : From your Update i think the easiest way in this case is to simply do:

models.TextField(db_index=True, default=lambda: cPickle.dumps(set()) 

And for why your first example wasn't working , it's because cPickle.dumps(set()) si not a callable you are evaluating cPickle.dumps(set()) when the model is defined.

Hope it can help :)

mouad
  • 67,571
  • 18
  • 114
  • 106
  • @Rosarch : you have to put the name of your model , i named __MyModel__ just as an example :) – mouad Jan 13 '11 at 01:50
  • @Rosarch: i just edited my answer sorry for that , now i have tested and it work , hope it can help :) – mouad Jan 13 '11 at 02:38
  • @Rosarch: i have just run the tests just like you did and i didn't get any error !!! i can't tell why you do get an error there but i can tell you that in my case the test doesn't fail so you have to check something else , well hope you find the answer :) – mouad Jan 13 '11 at 11:29