[Django]-Django REST: serializer field that isn't a model field

4👍

The take away is that in a serializer method of your Book model, you have access to context which provides context['request'].user and obj which represents the Book object

I will assume your ReadBy has an FK to Book, otherwise it’s not clear how you link them together

class ReadBy(models.Model):
   created = models.DateTimeField(auto_now_add=True)
   owner = models.ForeignKey(MyUser)
   book = models.ForeignKey(Book)

Let’s make a BookSerializer

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book

    has_been_read_by = serializers.SerializerMethodField('get_has_been_read_by')

    def get_has_been_read_by(self, obj):
        user = self.context['request'].user
        book = obj

        # See if a ReadBy object exists
        return ReadBy.objects.filter(book=book, owner=user).exists()

That field will contain either True or False, as booleans, which will be translated to your REST format, e.g. JSON (or you can return true and false strings just as easily)

Now use it in your ViewSet e.g.

class BookViewSet(viewsets.ModelViewSet):
    model = Book
    serializer_class = BookSerializer
👤bakkal

Leave a comment