第一次在这里问,我会听起来很聪明! 因此,我有一个名为“ Article”的模型,并在其中的“ text”字段中填充了1000多个字符。如何做到这一点,以便在通过端点发送“ Article”序列化对象时只发送“ text”字段的前200个字符?
views.py
class ArticleScrape(generics.ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def list(self,request):
serializer = ArticleSerializer(queryset, many=True)
return Response(serializer.data)
serializers.py
class ArticleSerializer(serializers.ModelSerializer):
authors = EachAuthorSerializer(many=True,read_only=True)
tags = EachTagSerializer(many=True,read_only=True)
text = serializers.CharField(max_length=200)
class Meta:
model = Article
exclude=('id',)
我需要在查询集中执行此操作吗?在序列化器中?我是否要注释字段?我已经尝试了很多这种方法,但都没有成功。预先感谢您的帮助!
答案 0 :(得分:1)
有不同的方法,我更喜欢的第一种方法是向模型添加属性,并将其字段添加到序列化器:
class Article(models.Modle):
...
@property
def summary(self):
return self.text[:200]
class ArticleSerializer(serializers.ModelSerializer):
summary = serializers.CharField()
对于第二种方法,您可以使用SerializerMethodField:
class ArticleSerializer(serializers.ModelSerializer):
summary = serializers.SerializerMethodField()
def get_summary(self, obj):
return obj.text[:200]
答案 1 :(得分:0)
另一种方法是创建自己的自定义字段:
class CustomCharField(serializers.CharField):
def __init__(self, repr_length, **kwargs):
self.repr_length = repr_length
super(CustomCharField, self).__init__(**kwargs)
def to_representation(self, value):
return super(CustomCharField, self).to_representation(value)[:self.repr_length]
并在序列化程序中使用它:
class ArticleSerializer(serializers.ModelSerializer):
text = CustomCharField(repr_length=200)
答案 2 :(得分:0)
我喜欢zeynel建议的“ CustomCharField”方法。此版本使用Django的Truncator。
from django.utils.text import Truncator
from rest_framework import serializers
class TruncatedCharField(serializers.CharField):
def __init__(self, length=200, **kwargs):
self.length = length
super().__init__(**kwargs)
def to_representation(self, value):
repr_ = super().to_representation(value)
return Truncator(repr_).chars(self.length)