[Fixed]-How to default IntegerField in Django


Django uses the save() method to actually save the data. You may overwrite it like so:

class Suit(models.Model):
    def save(self):
        if self.suit_length == 0:
            self.suit_length = self.customer.height
        super(Suit, self).save()

It is not overwriting the default, but it achieves your goal.



You want an invariant to be true at run-time, which is that the initial length of a Suit is equal to the height of a Customer.

Doesn’t the pythonic way to do this involve __ init __() ?

    class Suit(models.Model)
        customer = models.ForeignKey(Customer)
        suit_design = models.CharField(max_length=500)
        suit_length = models.IntegerField(default=lambda:self.customer.height)

        def __init__(self, args, kwargs):
            super(models.Model, args, kwargs)
            if kwargs['customer']:
                self.customer = kwargs['customer']
                # this creates the invariant
                self.suit_length = self.customer.height  
                raise ValueError("Must have a customer before constructing a Suit")
            # More code for suit_design, etc.

Leave a comment