Return default value for empty field in django model

I have a model where one field is often an empty string. Is there a way to return (for example) the string "default" instead of this empty string for queries against this model?

class MyModel(models.Model):
    ...
    afield = models.CharField(...)  # many rows set afield to ''

      

When I make a request

o = MyModel.objects.all()
vars(o[0])
{...
'afield': ''  # afield is empty
...}

      

I would rather see

vars(o[0])
{...
'afield': 'default'
...}

      

Is there a way to do this? Is there a better way to implement this than inside the model?

Notes:

  • I don't want to store the string 'default'
  • this answer changes the database, i want to avoid this
+1


source to share


2 answers


Most likely much better handle this in views as part of your logic, but you can use properties and setters to do this:



class MyModel(models.Model):
    _afield = models.CharField(...)
    @property
    def afield(self):
        if self._afield:
            return self._afield
        else:
            return "default"

    @afield.setter
    def afield_setter(self,value):
        self._afield = value

      

+1


source


You can override the __ getattribute __ () method:

class MyModel(models.Model):
    ....
    def __getattribute__(self, name):
        attr = models.Model.__getattribute__(self, name)
        if name == 'afield' and not attr:
            return 'default'
        return attr

      



Here is the usage:

>>> obj = MyModel()
>>> obj.afield
'default'
>>> getattr(obj, 'afield')
'default'
>>> obj.afield = 'test'
>>> obj.afield
'test'
>>> getattr(obj, 'afield')
'test'
>>> obj.afield = ''
>>> obj.afield
'default'
>>> # other properties work as usual
>>> obj.some_var = 123
>>> obj.some_var
123

      

+3


source







All Articles