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 8116133
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T03:43:12+00:00 2026-06-06T03:43:12+00:00

I have written a custom Django Model Field to store dateutil.relativedelta ‘s. The field

  • 0

I have written a custom Django Model Field to store dateutil.relativedelta‘s. The field looks like this:

class RelativeDeltaField(models.CharField):
    description = "Relative delta"

    __metaclass__ = models.SubfieldBase

    max_length = 200

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = self.max_length
        super(RelativeDeltaField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if isinstance(value, relativedelta):
            return value

        try:
            return eval(value)
        except SyntaxError, e:
            logging.error("Mangled data for a relativedelta field. Was the data truncated in MySQL column? Either manually fix, or change the next line to 'return None' and manually fix. value=%r message=%r" % (value, e))
            raise

    def get_db_prep_save(self, value, connection):

        return repr(value)

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

I am trying to serialise an object with this field to json with:

serializers.serialize('json', obj)

But I get an error:

…
  File "/home/rory/tix/virtualenv/lib/python2.6/site-packages/django/core/serializers/json.py", line 58, in default
    return super(DjangoJSONEncoder, self).default(o)
  File "/usr/lib/python2.6/dist-packages/simplejson/encoder.py", line 190, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: relativedelta(hours=+1) is not JSON serializable

From using the pdb, I can see that o in this case is the object itself, it hasn’t been converted to anything, nor serialised.

How do I fix this so I can serialise my field?

The Django documentation says ( https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#converting-field-data-for-serialization ) to add a value_to_string, which I do have.

  • 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-06T03:43:13+00:00Added an answer on June 6, 2026 at 3:43 am

    The code in the doc is just a boilerplate, you need to implement value_to_string to return a string representing the relativedelta.

    The RelativeDeltaField is based on models.CharField, thus the get_prep_value() looks like

    def get_prep_value(self, value):
        return self.to_python(value)
    

    It’s OK for CharField because the intended value in Python of the field is already a string. However, your customized version of to_python() returns relativedelta instead of string.

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

Sidebar

Related Questions

I have written a custom server control which (pseudo-code) looks like public class MyCustomCtrl
I have written the following custom field: from django.core.urlresolvers import reverse from django.db import
I have written a custom class to handle database queries to a remote and
I have written a custom class for overriding the seek method of QSlider. Basically
Assume i have a custom Windows application written in C#. This application has only
I have written a custom SessionStoreProvider class that inherits from the SessionStateStoreProviderBase. I have
I have written a custom class that depends significantly on touch dragging/positioning, outside of
I have written a JSP custom tag, implemented in a class that extends TagSupport,
I have written 2 custom template tags in Django. The goal is to use
I have written a custom model binder for List in my MVC project however

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.