code_junkie

Unique fields that allow nulls in Django

Nov 13th, 2011
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. class Foo(models.Model):
  2. name = models.CharField(max_length=40)
  3. bar = models.CharField(max_length=40, unique=True, blank=True, null=True, default=None)
  4.  
  5. CREATE TABLE appl_foo
  6. (
  7. id serial NOT NULL,
  8. "name" character varying(40) NOT NULL,
  9. bar character varying(40),
  10. CONSTRAINT appl_foo_pkey PRIMARY KEY (id),
  11. CONSTRAINT appl_foo_bar_key UNIQUE (bar)
  12. )
  13.  
  14. insert into appl_foo ("name", bar) values ('test1', null)
  15. insert into appl_foo ("name", bar) values ('test2', null)
  16.  
  17. class FooForm(forms.ModelForm):
  18. class Meta:
  19. model = Foo
  20. def clean_bar(self):
  21. bar = self.cleaned_data['bar']
  22. if bar == '':
  23. bar = None
  24. return bar
  25.  
  26. class FooAdmin(admin.ModelAdmin):
  27. form = FooForm
  28.  
  29. from django.db import models
  30.  
  31. class CharNullField(models.CharField): #subclass the CharField
  32. description = "CharField that stores NULL but returns ''"
  33. def to_python(self, value): #this is the value right out of the db, or an instance
  34. if isinstance(value, models.CharField): #if an instance, just return the instance
  35. return value
  36. if value==None: #if the db has a NULL (==None in Python)
  37. return "" #convert it into the Django-friendly '' string
  38. else:
  39. return value #otherwise, return just the value
  40. def get_db_prep_value(self, value): #catches value right before sending to db
  41. if value=="": #if Django tries to save '' string, send the db None (NULL)
  42. return None
  43. else:
  44. return value #otherwise, just pass the value
  45.  
  46. def save(self):
  47. """overriding save method so that we can save Null to database, instead of empty string (project requirement)"""
  48. # get a list of all model fields (i.e. self._meta.fields)...
  49. emptystringfields = [ field for field in self._meta.fields
  50. # ...that are of type CharField or Textfield...
  51. if ((type(field) == django.db.models.fields.CharField) or (type(field) == django.db.models.fields.TextField))
  52. # ...and that contain the empty string
  53. and (getattr(self, field.name) == "") ]
  54. # set each of these fields to None (which tells Django to save Null)
  55. for field in emptystringfields:
  56. setattr(self, field.name, None)
  57. # call the super.save() method
  58. super(MyModel, self).save()
  59.  
  60. def save(self, *args, **kwargs):
  61.  
  62. if not self.bar:
  63. self.bar = None
  64.  
  65. super(Foo, self).save(self, *args, **kwargs)
  66.  
  67. class Foo(models.Model):
  68. value = models.CharField(max_length=255, unique=True)
  69.  
  70. class Bar(models.Model):
  71. foo = models.OneToOneField(Foo, null=True)
Add Comment
Please, Sign In to add comment