Created
July 19, 2016 07:54
-
-
Save mikofski/d2452658d21ef22ab423fb7ba58745a0 to your computer and use it in GitHub Desktop.
django derived database field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment