default model field attribute in Django
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.thre开发者_如何学运维shold = 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.
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 :)
精彩评论