Title: Django model column
Tags: python;django
Question: How I can make a model field to return a default value from function?
class Q(models.Model):
_random_id = models.CharField(max_length=18)
@property
def random_id(self):
return self._random_id
@random_id.setter
def random_id(self):
self._random_id = f()
Comment: yeah but i need to add value from function f() as default

Comment: there is the `default` field option.  Each model will automatically have an `id` field that is unique for that model.. you

Comment: You can override your save mathod and if the record is new you can have random_id set to `f()`

Here is the accepted answer: From the documentation for default:
This can be a value or a callable object. If callable it will be called every time a new object is created.
So, you can pass it a function:
_random_id = models.CharField(max_length=18, default=f)
Q is the name of a built-in in django, so its best not to use it for your model.
Further,
@property
def random_id(self):
return self._random_id
This is only serving as syntactical sugar because you can refer to the _random_id field directly from an instance of the model:
foo = Q()
foo._random_id
So you should consider removing this property entirely; and if you need random_id, set it as the name of your field.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:07/13/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><django>', 'Title': 'Django model column', 'ViewCount': 71, 'id': 17633734, 'user_AboutMe': '<p>please delete me</p>\n', 'user_AccountId': 1477294.0, 'user_DisplayName': 'Xtal', 'user_Reputation': 295.0, 'user_Views': 55.0, 'user_id': 1387390.0}}