- Author:
- binishkaspar
- Posted:
- February 20, 2011
- Language:
- Python
- Version:
- 1.2
- Score:
- 0 (after 0 ratings)
Purpose
We often need to store x,y, width and height for a model, we can store all these values in same field by having custom field.
How to Use
Save this code in customfields.py and in your model
from customfields import FrameField class MyModel(models,Model) frame = FrameField()
And in your in views, you can use as follows
model = MyModel.objects.get(1) print model.frame.x, model.frame.y, model.frame.width, model.frame.height
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | class Frame(object):
#TODO: Missing Validateion and exception raising
def __init__(self, x, y, width, height):
self.x = float(x)
self.y = float(y)
self.width = float(width)
self.height = float(height)
@staticmethod
def Parse(value):
if value == '' or value is None:
return Frame(0,0,0,0)
(x, y, width, height) = value.split(',')
return Frame(x, y, width, height)
def __unicode__(self):
return "%f,%f,%f,%f" % (self.x, self.y, self.width, self.height)
class FrameField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
#self.max_length = 68
super(FrameField, self).__init__(*args, **kwargs)
def db_type(self, connection):
return 'char(%s)' % 68
def to_python(self, value):
if isinstance(value, Frame):
return value
return Frame.Parse(value)
def get_prep_value(self, value):
return self.to_python(value)
def get_db_prep_save(self, value, connection):
return self.to_python(value).__unicode__()
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.