Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8145007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T13:31:35+00:00 2026-06-06T13:31:35+00:00

I needed to store arbitrary data in a relational database of multiple data-types so

  • 0

I needed to store arbitrary data in a relational database of multiple data-types so I came up with a solution of in addition to storing the data itself also to store what is the datatype of the data (str, int, etc). This allows upon retreival to cast the string which is stored in the db into whatever proper data-type the data is. In order to store the data-type I made a custom model field:

class DataType(object):
    SUPPORTED_TYPES = {
        u'unicode': unicode,
        u'str': str,
        u'bool': bool,
        u'int': int,
        u'float': float
    }
    INVERSE_SUPPORTED_TYPES = dict(zip(SUPPORTED_TYPES.values(), SUPPORTED_TYPES.keys()))
    TYPE_CHOICES = dict(zip(SUPPORTED_TYPES.keys(), SUPPORTED_TYPES.keys()))

    def __init__(self, datatype=None):
        if not datatype:
            datatype = unicode

        t_datatype = type(datatype)

        if t_datatype in [str, unicode]:
            self.datatype = self.SUPPORTED_TYPES[datatype]

        elif t_datatype is type and datatype in self.INVERSE_SUPPORTED_TYPES.keys():
            self.datatype = datatype

        elif t_datatype is DataType:
            self.datatype = datatype.datatype

        else:
            raise TypeError('Unsupported %s' % str(t_datatype))

    def __unicode__(self):
        return self.INVERSE_SUPPORTED_TYPES[self.datatype]

    def __str__(self):
        return str(self.__unicode__())

    def __len__(self):
        return len(self.__unicode__())

    def __call__(self, *args, **kwargs):
        return self.datatype(*args, **kwargs)


class DataTypeField(models.CharField):
    __metaclass__ = models.SubfieldBase
    description = 'Field for storing python data-types in db with capability to get python the data-type back'

    def __init__(self, **kwargs):
        defaults = {}
        overwrites = {
            'max_length': 8
        }
        defaults.update(kwargs)
        defaults.update(overwrites)
        super(DataTypeField, self).__init__(**overwrites)

    def to_python(self, value):
        return DataType(value)

    def get_prep_value(self, value):
        return unicode(DataType(value))

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        return self.get_prep_value(val)

So this allows me to do something like that:

class FooModel(models.Model):
    data = models.TextField()
    data_type = DataTypeField()

>>> foo = FooModel.objects.create(data='17.94', data_type=float)
>>> foo.data_type(foo.data)
17.94
>>> type(foo.data_type(foo.data))
float

So my problem is that in the Django Admin (I am using ModelAdmin), the value for data_type in the textbox does not show up properly. Whenever it is float (and in db it is stores as float, I checked), the value displayed is 0.0. For int it displays 0. For bool it displays False. Instead of showing the string representation of the data_type, somewhere Django actually calls it, which means the __call__ is called withour an parameters, which results in those values. For example:

>>> DataType(float)()
0.0
>>> DataType(int)()
0
>>> DataType(bool)()
False

I figured out how to monkey patch it by replacing __call__ method with the following:

def __call__(self, *args, **kwargs):
    if not args and not kwargs:
        return self.__unicode__()
    return self.datatype(*args, **kwargs)

This displays the correct value in the form however I feel that this is not very elegant. Is there any way to make it better? I could not figure out where Django called the field value in the first place.

Thanx

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T13:31:37+00:00Added an answer on June 6, 2026 at 1:31 pm

    wrt why your DataType get called, read this: https://docs.djangoproject.com/en/1.4/topics/templates/#accessing-method-calls

    The clean solution might be to simply rename call to something more explicit.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a MarshalByRefObject which I needed to serialize and store (in a database),
I have some questions about when it is needed to store the data in
I'm using ASP.NET MVC 2 and stuck with the situation when needed to store
Recently in a project I am working on, I needed to store callbacks in
How to insert multiple data into mssql without using loop? i'm developing a clinic
I need to store passwords in my SQL database. Too high security is not
I’m creating an application that uses Core Data to store information and uses web
My database must be updated at arbitrary intervals, manually, with new info to put
I have a requirement whereby I needed to store a simple cache of a
Previously, when I needed to store a number of related variables, I'd create a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.