Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Foo(models.Model):
- name = models.CharField(max_length=40)
- bar = models.CharField(max_length=40, unique=True, blank=True, null=True, default=None)
- CREATE TABLE appl_foo
- (
- id serial NOT NULL,
- "name" character varying(40) NOT NULL,
- bar character varying(40),
- CONSTRAINT appl_foo_pkey PRIMARY KEY (id),
- CONSTRAINT appl_foo_bar_key UNIQUE (bar)
- )
- insert into appl_foo ("name", bar) values ('test1', null)
- insert into appl_foo ("name", bar) values ('test2', null)
- class FooForm(forms.ModelForm):
- class Meta:
- model = Foo
- def clean_bar(self):
- bar = self.cleaned_data['bar']
- if bar == '':
- bar = None
- return bar
- class FooAdmin(admin.ModelAdmin):
- form = FooForm
- from django.db import models
- class CharNullField(models.CharField): #subclass the CharField
- description = "CharField that stores NULL but returns ''"
- def to_python(self, value): #this is the value right out of the db, or an instance
- if isinstance(value, models.CharField): #if an instance, just return the instance
- return value
- if value==None: #if the db has a NULL (==None in Python)
- return "" #convert it into the Django-friendly '' string
- else:
- return value #otherwise, return just the value
- def get_db_prep_value(self, value): #catches value right before sending to db
- if value=="": #if Django tries to save '' string, send the db None (NULL)
- return None
- else:
- return value #otherwise, just pass the value
- def save(self):
- """overriding save method so that we can save Null to database, instead of empty string (project requirement)"""
- # get a list of all model fields (i.e. self._meta.fields)...
- emptystringfields = [ field for field in self._meta.fields
- # ...that are of type CharField or Textfield...
- if ((type(field) == django.db.models.fields.CharField) or (type(field) == django.db.models.fields.TextField))
- # ...and that contain the empty string
- and (getattr(self, field.name) == "") ]
- # set each of these fields to None (which tells Django to save Null)
- for field in emptystringfields:
- setattr(self, field.name, None)
- # call the super.save() method
- super(MyModel, self).save()
- def save(self, *args, **kwargs):
- if not self.bar:
- self.bar = None
- super(Foo, self).save(self, *args, **kwargs)
- class Foo(models.Model):
- value = models.CharField(max_length=255, unique=True)
- class Bar(models.Model):
- foo = models.OneToOneField(Foo, null=True)
Add Comment
Please, Sign In to add comment