2 回答
TA贡献1812条经验 获得超5个赞
您可以连接全名,将其注释到查询集上,然后将其添加到序列化程序中:
from django.db.models import F, Value
class ArticlesViewset(viewsets.ModelViewSet):
permission_classes = [permissions.AllowAny]
queryset = Articles.objects.all()
serializer_class = ArticleSerializer
def get_queryset(self):
return self.queryset.annotate(
authors_name=Concat('author__first_name', Value(" "), 'author__last_name')
)
class ArticleSerializer(serializers.ModelSerializer):
authors_name = serializers.CharField(required=False)
class Meta:
model = Articles
fields = ('article_title', 'description', 'created_at', 'authors_name')
TA贡献1852条经验 获得超7个赞
我在序列化程序类中进行了以下更改,并且能够获取作者姓名
#Article serializer
class ArticleSerializer(serializers.ModelSerializer):
author = serializers.CharField(required=False)
class Meta:
model = Articles
fields = ('article_title', 'description','created_at', 'author')
添加回答
举报