3

Is there a way to automatically set field values for models in Django when defining the model? This could be used for storing something like a timestamp (for example), but also for creating a field which is constructed as some function of the others.

In other words, I'm looking for something like this:

class Foo(models.Model):

spam = models.CharField(max_length=2000)
my_other_field = ###?

def generate_my_other_field():
    #Some algorithm to determine the value of my_other_field
2
  • 1
    Do you want to store these generated values in the database? Or just have them available when you're looking at the model instances? Commented Jul 10, 2011 at 21:01
  • I'd like to generate them when the other fields are defined as well - basically, the way an initializer would work in Python. There might be a cleaner way to do this, but it's the easiest that I can think of. Commented Jul 10, 2011 at 21:13

1 Answer 1

6

Yes, there is a way. From Django docs:

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I didn't realize that default values could be callable functions.
The trick is to make sure you assign the function as the default, not the result - so (eg) default=datetime.datetime.now rather than default=datetime.datetime.now().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.