如何将额外的上下文传递给Django Rest Framework序列化程序 [英] How to pass extra context to Django Rest Framework serializers
问题描述
这是我第一个使用Django rest框架的项目,而我正努力做到这一点。我知道在主流Django框架中,如果需要在基于类的视图中添加额外的上下文,我将执行以下操作:
It is my first project using Django rest framework and i'm struggling to get this right. I know that in mainstream Django framework, if i need to add extra contexts to a class-based view, i will do something like this:
class PostDetail(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books by a certain author John
context['john_books'] = Book.objects.filter(author=john)
return context
然后,我将能够访问模板中的上下文 john_books。现在,我需要通过将额外的上下文传递给我的PostViewSets来执行相同的操作。在详细信息视图上,我想访问该帖子作者在我的api端点中撰写的帖子列表(类似于同一作者的帖子)。我已经读过有关 get_serializer_context
的信息,但仍然不知道如何实现。这是我到目前为止所拥有的:
then, i will be able to access the context 'john_books' in my template. Now i need to do same by passing extra contexts to my PostViewSets. On the detail view, i want to access the list of post authored by that post author in my api endpoint (something like 'Posts from the same author'). I have read about get_serializer_context
but still can't figure out how to implement it. This is what i have so far:
class PostViewSets(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_serializer_context(self):
context = super(PostViewSets, self).get_serializer_context()
author = self.get_object.author
author_posts = self.get_queryset().filter(author=author)
context.update({'author_posts': author_posts})
return context
我得到这个错误:
AttributeError at / posts /'function'对象没有属性'author'
AttributeError at /posts/ 'function' object has no attribute 'author'
我的帖子模型:
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
body = models.TextField()
is_featured = models.BooleanField(default=True)
viewcount = models.IntegerField(default=0)
author = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
和我的PostSerializer类:
and my PostSerializer class:
class PostSerializer(serializers.ModelSerializer):
author = UserSerializer()
class Meta:
model = Post
fields = ['id', 'title', 'body', 'author', 'viewcount', 'is_featured', 'created']
推荐答案
您必须使用 get_object
作为函数,而不是作为属性:
You have to use get_object
as func, not as property:
class PostViewSets(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_serializer_context(self):
context = super(PostViewSets, self).get_serializer_context()
author = self.get_object().author
author_posts = self.get_queryset().filter(author=author)
context.update({'author_posts': author_posts})
return context
这篇关于如何将额外的上下文传递给Django Rest Framework序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!