Andy
Andy

Reputation: 738

General Django Rest Question on Serializers

Quick concept question for you. I am working through a Django tutorial that involves building an api backend via django(using v 2.1). I have the following serializer for handling Comment objects from my Comment model in my articles app.

class CommentSerializer(serializers.ModelSerializer):
author = ProfileSerializer(required=False)

createdAt = serializers.SerializerMethodField(method_name='get_created_at')
updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

class Meta:
    model = Comment
    fields = (
        'id',
        'author',
        'body',
        'createdAt',
        'updatedAt',
    )

def create(self, validated_data):
    article = self.context['article']
    author = self.context['author']

    return Comment.objects.create(
        author=author, article=article, **validated_data
    )

I want better understand this section of code:

def create(self, validated_data):
    article = self.context['article']
    author = self.context['author']

Specifically where is 'context' coming from? I have enough of an understanding of what exactly is going on here, I am more or less just curious of the mechanics behind what's going on here. For instance we didn't state context as an argument variable in the create function. Is context coming from my model? Is there some django magic taking place in the rest_framework that is assigning (maybe the entire instance) the context variable?

Thanks everyone!

Upvotes: 0

Views: 44

Answers (1)

ruddra
ruddra

Reputation: 51938

Actually this is related to extra context. You can pass it to serializer from View and use it in the serializer. For example:

def post_comment(request, article_id):
    post_data = request.data
    article = Article.objects.get(pk=article_id)
    context = {'author': request.user, 'article':article}
    serializer = YourSerializer(data=data, context=context)  # <--- You are passing context from view
    # This is the very same context you are catching in your create method
    if serializer.is_valid():
         serializer.save()
         # rest of your code

Upvotes: 1

Related Questions