序列化器上的Django通用其余问题

时间:2018-11-30 22:07:08

标签: python django django-rest-framework

为您提供的快速概念问题。我正在研究Django教程,该教程涉及通过django(使用v 2.1)构建api后端。我有以下序列化程序,用于在我的文章应用中处理我的Comment模型中的Comment对象。

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
    )

我想更好地理解这段代码:

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

“上下文”具体来自哪里?我对这里到底发生了什么有足够的了解,我或多或少对这里发生的事情背后的机制感到好奇。例如,我们没有在create函数中将上下文声明为参数变量。背景是否来自我的模型?在分配(可能是整个实例)上下文变量的rest_framework中是否发生了一些django魔术?

谢谢大家!

1 个答案:

答案 0 :(得分:1)

实际上,这与extra context有关。您可以将其从View传递给序列化器,并在序列化器中使用它。例如:

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