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

72 - Feature request: Omission of certain fields in models on JSON serialization #71

Open
klipstein opened this issue Nov 6, 2011 · 0 comments

Comments

@klipstein
Copy link
Owner

A lot of the times, I want to serialize an object, but not send all of its properties. This becomes cumbersome with Django models.

There should be some way to tell the serializer what fields to skip or include, in the same way as with the built-in Django JSON serializer.

I've made a custom hack for this - I am sure this could be solved in some more elegant way.

Diff on util/**init**.py:

<             # special FileField handling (they can't be json serialized)
<             if isinstance(f, ImageField) or isinstance(f, FileField):
<                 ret[f.attname] = unicode(getattr(data, f.attname))
<             else:
## <                 ret[f.attname] = _any(getattr(data, f.attname))

>            if not (hasattr(data, 'CustomMeta') and hasattr(data.CustomMeta, 'serialize_fields') and not f.attname in data.CustomMeta.serialize_fields):
>                # special FileField handling (they can't be json serialized)
>                if isinstance(f, ImageField) or isinstance(f, FileField):
>                    ret[f.attname] = unicode(getattr(data, f.attname))
>                else:
>                    ret[f.attname] = _any(getattr(data, f.attname))
158c159
## <         add_ons = [k for k in dir(data) if k not in fields and k not in ('delete', '_state',)]

>         add_ons = [k for k in dir(data) if k not in fields and k not in ('delete', '_state',) and not (hasattr(data, 'CustomMeta') and hasattr(data.CustomMeta, 'serialize_fields') and not f.attname in data.CustomMeta.serialize_fields)]

How it's used in a model:

class MyModel(Model):
    id = CharField(max_length=24, primary_key=True)
    name = CharField(max_length=20)
    secret = CharField(max_length=20)
    class CustomMeta:
        serialize_fields = ('id', 'name')

Original link: http://code.google.com/p/dojango/issues/detail?id=72
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

1 participant