How to create a django model field that has a default value if ever set to null

Given the model

class Template(models.Model):
    colour = models.CharField(default="red", blank = True, null=True)

      

How can I organize it so that any color access will return the value stored in the field, or if the field is empty / null it returns red?

default = red
will put "red" in the box when it is created, but if it is edited to empty I would like to access it to return "red" rather than ""

Updated: I tried the properties solution suggested below, but I am using JSON serialization to implement REST API and properties (for example colour

) do not get serialized and serialization _colour

breaks API

+1


source to share


3 answers


This is how I went about solving this problem.

Some prerequisites first: I have existing code that accesses these field names (like "color") and the field is also serialized (via django-rest-interface) as part of the API. None of these things can be changed.

The attempted property method worked fine, except that it was colour

no longer a field, so it was not serialized. Result: broken API

It will then move to the save () solution along with a custom attribute for each field, which should behave like this:



class ColourChoices(models.Model):
    colour1 = models.CharField()
    colour1.colour_default = "red"
    colour2 = models.CharField()
    colour2.colour_default = "blue"

    def save(self, *args, **kwargs):
        # force colour fields to default values
        for f in [ x for x in self._meta.fields if hasattr(x, 'colour_default') ]:
            if self.__getattribute__(f.attname) == "":
                self.__setattr__(f.attname, f.colour_default)
       super(ColourChoices, self).save(*args,**kwargs)

      

Now everything works fine and as needed.

The only problem with this solution is that if the defaults change, there is no way to determine which database fields should have the updated defaults and which just happen to coincide with the old default. However, for my application, I can live with this.

0


source


You can create a separate method instead:

def get_colour(self):
    if not self.colour:
        return 'red'
    else:
        return self.colour

      



An alternative is to use the property.

http://www.djangoproject.com/documentation/models/properties/

+4


source


Use a method save

to implement it.

def save( self, *args, **kw ):
    if self.colour is None:
        self.colour= 'red'
    super( ThisModel, self ).save( *args, **kw )

      

+1


source







All Articles