Adding field conditionally based another attribute of a model instance

52 views
Skip to first unread message

Val Neekman

unread,
Mar 11, 2014, 12:18:34 AM3/11/14
to django-res...@googlegroups.com
How about this:

Your users have the option (visibility) to have their emails public, private or view by members only.

How do you go about only showing the email when the visibility is set to public or if user is logged in.

Any better option that this?

class ProfileListSerializer(serializers.ModelSerializer):
    """
    Profile serializer for retrieving a user instance.
    """
    email = serializers.SerializerMethodField('get_email')

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', visibility', 'email', )


    def get_email(self, obj):
        email = ''
        if obj.visibility == User.VISIBILITY_PUBLIC:
            email = obj.email
        elif obj.visibility == User.VISIBILITY_MEMBERS:
            req = self.context.get('request', None)
            if req is not None and req.user.is_authenticated():
                email = obj.email
        return email


Malcolm Box

unread,
Apr 3, 2014, 6:20:05 AM4/3/14
to django-res...@googlegroups.com
Two ways to do this occur to me:

- at the view layer, pick a different serialiser depending on the value of the attribute. This would work well when there's a large number of fields that depend on that attribute e.g. for logged in or anon users
- In the serializer, in the way you've done it. Works well when specific fields have field-specific serializations

As a *consumer* of the API, it's much nicer if fields are predictably there, even if the value is None/null/empty, rather than having the entire field disappear. There are JSON parsers (notably in the Java world) that try to do JSON <-> Object mappings and get quite upset if a field isn't there or changes type.

Malcolm

Rodrigo Gadea

unread,
Apr 3, 2014, 7:17:08 PM4/3/14
to django-res...@googlegroups.com

On Thu, Apr 3, 2014 at 7:20 AM, Malcolm Box <mal...@tellybug.com> wrote:
As a *consumer* of the API, it's much nicer if fields are predictably there, even if the value is None/null/empty, rather than having the entire field disappear. There are JSON parsers (notably in the Java world) that try to do JSON <-> Object mappings and get quite upset if a field isn't there or changes type.

+1
Reply all
Reply to author
Forward
0 new messages