Xtal
Xtal

Reputation: 305

Django model column

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

Upvotes: 0

Views: 74

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

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.

Upvotes: 1

Related Questions