Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

problem subclassing and overriding from_db_value #32

Closed
tisdall opened this issue Aug 4, 2017 · 2 comments
Closed

problem subclassing and overriding from_db_value #32

tisdall opened this issue Aug 4, 2017 · 2 comments

Comments

@tisdall
Copy link

tisdall commented Aug 4, 2017

I recently upgraded from Django 1.7 to 1.8 and have run into problems with a subclassed PickledObjectField. The code looks like this:

from picklefield.fields import PickledObjectField as OriginalPickledObjectField

class PickledObjectField(OriginalPickledObjectField):
    """ Modified to return an empty `dict` object if empty """

    def to_python(self, value):
        return super(PickledObjectField, self).to_python(value) or {}

I had some spots where the field was sometimes None/NULL but wanted to treat those as equivalent to an empty dictionary. It worked fine until I upgraded to Django 1.8 .

I saw that in 1.8 it stops using the models.SubfieldBase metaclass and instead used from_db_value. I think the existing from_db_value, which calls to_python, should be fine but the field returns as None instead of an empty dict. I tried overriding the method to call my to_python, but for some reason it doesn't even get called!

I'm totally stumped as to what's going wrong.

@tisdall
Copy link
Author

tisdall commented Aug 4, 2017

I think the issue is from_db_value isn't called on assignment where the old system with the metaclass caused the to_python to be called.

Are there any suggestions on how to modify my subclass such that NULL values can be treated like an empty dict?

@charettes
Copy link
Collaborator

Sorry for the delay on the reply here. It looks like Django's from_db_value introduction includes guidelines on how such a behavior can be restored.

From Django 1.8 release notes

The new approach doesn’t call the to_python() method on assignment as was the case with SubfieldBase. If you need that behavior, reimplement the Creator class from Django’s source code in your project.

I'll close this for now as this has become the de-facto behavior of model fields at this point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants