class CommentSerializers1(serializers.ModelSerializer): author = UserSerializers() news = NewsSerializers() class Meta: model = models.Comment fields = "__all__"
def get(self, request, format=None): rol = request.user.is_superuser if rol == True: queryset = User.objects.all() serializer = UserSerializers(queryset, many=True) return Response(serializer.data) else: return Response("No eres administrador")
class CommentSerializers(serializers.ModelSerializer): author = UserSerializers() news = NewsSerializers() sub_comment = CommentSerializers1(many=True) class Meta: model = models.Comment fields = "__all__"
class NewsSerializers(serializers.ModelSerializer): # 当访问tag这个字段时,会自动去访问NewsSerializers()这个函数 tag = TagSerializers() author = UserSerializers() class Meta: model = models.News # 其中‘tag’,'author',是通过外键引入的,需要分别再去写一个序列化,告诉以后当需要category字段的时候需要提取哪些字段。 fields = ('id', 'title', 'digest', 'image_url', 'create_time', 'tag', 'author', 'update_time', 'is_delete')
def get(self, request, id, format=None): rol = request.user.is_superuser if rol == True: example = self.get_object(id) if example != False: serializer = UserSerializers(example) return Response(serializer.data) else: return Response(status=status.HTTP_400_BAD_REQUEST) else: Response("No eres administrador")