Making Serializers output full GET representation while POSTing with PK's only

33 views
Skip to first unread message

Mike C Leach

unread,
May 9, 2013, 5:56:28 PM5/9/13
to django-res...@googlegroups.com
I have a model Vote:

class Vote(models.Model):
user = models.ForeignKey(User)
What I'm trying to achieve is a GET representation that has selected user details available, along with POST requests to create a vote that only require the pk of the user in question. Currently POST requests result in an error about missing fields on the user object.

I.E. GET /votes/1/ should return
{
"user": {
            "pk": 2, 
            "username": "brobot"
    }, 
    "pk": 1
}

while I should be able to create a new vote via POST /votes/ with data
{ "user":2 }

Do I intercept the request before validation and use the User.objects.get(pk=user_pk) to get a fully formed object, and then load that into request.DATA and allow validation and saving to continue? Or am I misunderstanding how to write the serializer and there is an easier way to define what's minimally acceptable to create via POST versus the more complete representation obtained via GET? I assume it would related to using PrimaryKeyRelatedField but there is a paucity of examples for PKField usage versus HyperlinkedFields, especially relating to nested objects. Here is my current serializer code.

Current Serializer code:
class UserSerializer(serializers.ModelSerializer):
    pk = serializers.Field()
    
    class Meta:
        model = User
        fields = ('pk', 'username',)


class VoteSerializer(serializers.ModelSerializer):
    pk = serializers.Field()
    user = UserSerializer()
    
    class Meta:
        model = Vote
        fields = ( 'user', 'pk',)


Thanks for any assistance you can provide.
Reply all
Reply to author
Forward
0 new messages