gpt4 book ai didi

python - 将用户特定字段添加到 Django REST Framework 序列化程序

转载 作者:太空狗 更新时间:2023-10-29 17:37:02 26 4
gpt4 key购买 nike

我想向序列化程序添加一个字段,其中包含特定于发出当前请求的用户的信息(我不想为此创建单独的端点)。这是我的做法:

View 集:

class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
filter_class = ArticleFilterSet

def prefetch_likes(self, ids):
self.current_user_likes = dict([(like.article_id, like.pk) for like in Like.objects.filter(user=self.request.user, article_id__in=ids)])

def get_object(self, queryset=None):
article = super(ArticleViewSet, self).get_object(queryset)
self.prefetch_likes([article.pk])
return article

def paginate_queryset(self, queryset, page_size=None):
page = super(ArticleViewSet, self).paginate_queryset(queryset, page_size)
if page is None:
return None

ids = [article.pk for article in page.object_list]
self.prefetch_likes(ids)

return page

序列化器:

class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article

def to_native(self, obj):
ret = super(ArticleSerializer, self).to_native(obj)

if obj:
view = self.context['view']
ret['has_liked'] = False
if hasattr(view, 'current_user_liked'):
ret['has_liked'] = obj.pk in view.current_user_liked

return ret

有没有更好的地方来注入(inject)喜欢的文章的预取,或者一般来说有更好的方法来做到这一点?

最佳答案

您可以使用 SerializerMethodField

示例:

class PostSerializer(serializers.ModelSerializer):
fav = serializers.SerializerMethodField('likedByUser')

def likedByUser(self, obj):
request = self.context.get('request', None)
if request is not None:
try:
liked=Favorite.objects.filter(user=request.user, post=obj.id).count()
return liked == 1
except Favorite.DoesNotExist:
return False
return "error"

class Meta:
model = Post

那么你应该像这样从 View 中调用序列化程序:

class PostView(APIVIEW):
def get(self,request):
serializers = PostSerializer(PostObjects,context={'request':request})

关于python - 将用户特定字段添加到 Django REST Framework 序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com