code_junkie

Django - Custom virtual model field with companion stored field [closed]

Nov 13th, 2011
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. class MyModel(models.Model):
  2. confirmation = ConfirmationField()
  3.  
  4.  
  5. m = MyModel()
  6. m.confirmation # False
  7. m.confirmation_timestamp # None
  8.  
  9. m.confirmation = True
  10. m.save()
  11.  
  12. m.confirmation_timestamp # datetime object
  13.  
  14.  
  15. m.confirmation = False
  16. m.save()
  17.  
  18. m.confirmation_timestamp # None again
  19.  
  20. def get_attname(self):
  21. return '%s_id' % self.name
  22.  
  23. if self.field.width_field:
  24. setattr(self.instance, self.field.width_field, self.width)
  25. if self.field.height_field:
  26. setattr(self.instance, self.field.height_field, self.height)
  27.  
  28. value = {'BooleanField': True,
  29. 'DateTimeField': datetime.datetime.now(),
  30. 'DateField': datetime.date.today(),
  31. 'IntegerField': 1,
  32. }[instance._meta.get_field(field_name).get_internal_type()]
  33. setattr(instance, field_name, value)
  34.  
  35. class Modelname(models.Model):
  36. """(Modelname description)"""
  37.  
  38. confirmation_timestamp = models.DateTimeField(blank=True)
  39.  
  40. def _set_confirmation(self, value):
  41. if not value:
  42. self.confirmation_timestamp = None
  43. else:
  44. self.confirmation_timestamp = datetime.datetime.now()
  45.  
  46. def _get_confirmation(self):
  47. return bool(self.confirmation_timestamp)
  48.  
  49. confirmation = property(_get_confirmation, _set_confirmation)
  50. confirmation.short_description = "Confirmation"
  51. confirmation.boolean = True # have it nicely displayed in admin
Add Comment
Please, Sign In to add comment