Dmitry
Dmitry

Reputation: 2138

Django Model Field default value not applied when creating object manually

Say my object has a DecimalField with default set to 20. When I create an object in python and don't specify a value for that DecimalField, it's None.

How to make sure that default value is applied every time I don't supply a value?

class SomeModel(models.Model):
    """Demonstrate the flaw of the default value."""

    dec_field = models.DecimalField(default=1, blank=True, null=True)


my_model = SomeModel()
my_model.save()  # this is where I expect the dec_field to become Decimal('1.0')
                 # instead it's None

Upvotes: 0

Views: 1517

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

Make sure that your model and database are synchronized, either with a migration tool such as South, or by dropping the table and resyncing.

Upvotes: 3

Reinbach
Reinbach

Reputation: 771

The default should be set with what you have described, would need more info about your example. But if you wanted to override, or set the default manually you could do the following;

DEC_FIELD_DEFAULT = 20
class Example(models.Model):
    dec_field = models.DecimalField(default=DEC_FIELD_DEFAULT)

    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(self, *args, **kwargs)
        self.dec_field = DEC_FIELD_DEFAULT

Upvotes: 1

Related Questions