0

I use Django REST Framework and I have a django model class like this:

class Venue(models.Model):
    user=models.ForeignKey(User)

I would then want to serialize this:

from rest_framework import serializers
import models

class VenueSerializer(serializers.ModelSerializer):

    class Meta:

        model=models.Venue
        fields=('id','user','is_current_user')

where is_current_user is a boolean value, somehow like this

def is_current_user(self):
    return self.request.user==self.user

How can I do this? Do I have request somewhere in serializer? Or should I do this somewhere in the model?

Less convenient options are:

  • to send the current user id to the client in another way and compare there, but then I'd have to expose the user of each model to the client.
  • to iterate over the json after serialization
  • manually without the serializers create a json from a queryset

1 Answer 1

1

I would suggest using SerializerMethodField:

class VenueSerializer(serializers.ModelSerializer):
    class Meta:
        model=models.Venue
        fields=('id','user','is_current_user')

    def get_is_current_user(self, obj):
        return self.context['request'].user == obj.user
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.