Tuesday, July 19, 2016

Derived Django Database Field

The trick to this is creating a custom field and overloading pre_save. Pay special attention to the self.attname member that is set to the value. The source for DateField is a good example. Make sure that if you add any new attributes to the field in it's __init__ method you also add a corresponding deconstruct method.

from __future__ import unicode_literals
from django.db import models
class HeaderField(models.CharField):
"""
Custom field class based on :class:`~django.db.models.CharField` that
creates a unique header from the header, data source and site coordinates.
"""
def pre_save(self, model_instance, add):
"""
Create the header field the every time the model is saved.
"""
if add:
# if adding new record, replace tag spaces with underscores
header = model_instance.header.replace(' ', '_')
# XXX: if header changed later with spaces, only the first split used!
# get the tag from header
header = model_instance.header.split(' ', 1)
# save latitude and longitude with 3 decimal places
value = '%s %s %.3f %.3f' % (
header[0], model_instance.get_data_source_display(),
model_instance.latitude, model_instance.longitude
)
setattr(model_instance, self.attname, value)
return value
# Create your models here.
class MyModel(models.Model):
DATA_SOURCES = (
(10, 'Meteonorm'),
(17, 'NEDO')
)
data_source = models.IntegerField(choices=DATA_SOURCES)
latitude = models.FloatField()
longitude = models.FloatField()
header = HeaderField(max_length=50, default='', unique=True)
view raw models.py hosted with ❤ by GitHub

No comments:

Post a Comment

Fork me on GitHub