Login

TrueNoneField

Author:
diverman
Posted:
December 8, 2009
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

This custom model field is a variant of NullBooleanField, that stores only True and None (NULL) values. False is stored as NULL.

It's usefull for special purposes like unique/unique_together.

One small problem is here, that False is not lookuped as None.

This snippets is a response to 1830

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.db.models.fields import subclassing
from django.core import exceptions
from django.conf import settings
from django.db import models

class TrueNoneField(models.NullBooleanField):
    __metaclass__ = subclassing.SubfieldBase

    def db_type(self):
        if 'postgresql' in settings.DATABASE_ENGINE:
            return "boolean CHECK (%s <> false)" % self.get_attname_column()[1]
        else:
            return super(TrueNoneField, self).db_type()

    def to_python(self, value):
        if value in (True, 1):
            return True
        elif value in (False, 0, None):
            return None

        raise exceptions.ValidationError("This value must be either True or None.")

    def get_db_prep_save(self, value):
        return super(TrueNoneField, self).get_db_prep_save(self.to_python(value))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.