我正在接受 mariodev 的解决方案 - 因为它确实有效并且我最初的想法是。我确实扩展了我的要求并希望将预告功能应用于其他领域,因此我最终得到:
from django import forms
from rest_framework.compat import force_text
from rest_framework import serializers, fields
class TeaserField(fields.Field):
def __init__(self, teaser_length=None, original_field=None):
self.teaser_length = teaser_length
self.original_field = original_field
super(fields.Field, self).__init__()
def field_to_native(self, obj, field_name):
if(self.original_field != None):
field_name = self.original_field
value = getattr(obj, field_name)
return self.to_native(value)
def to_native(self, value):
def joinEm(chunk):
teaser = ''
i=0
while len(teaser) < self.teaser_length:
teaser += chunk[i] + '.'
i += 1
return teaser
chunk = value.split('.')
teaser = joinEm(chunk)
strongOpenTag = '<strong>'
strongOpen = teaser.find(strongOpenTag)
strongClose = teaser.find('</strong>')
if(strongOpen > 0 and strongClose < 0):
teaser = teaser.replace(strongOpenTag,'')
return force_text(teaser)
以前的解决方案
这是我目前的工作解决方案,很想知道对此的看法。
from django import forms
from rest_framework.compat import force_text
class TeaserField(fields.CharField):
def __init__(self, teaser_length=None, *args, **kwargs):
self.teaser_length = teaser_length
super(TeaserField, self).__init__(*args, **kwargs)
def to_native(self, value):
return force_text(value[:self.teaser_length])
class ArticleSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(many=False, read_only=True)
content = TeaserField(teaser_length=20)
class Meta:
model = models.Article
fields = (
'id'
,'title'
, 'date_added'
, 'content'
, 'user'
)
class IdeaSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(many=False, read_only=True)
teaser = myFields.TeaserField(teaser_length=200, original_field='content')
class Meta:
model = myModels.Idea
fields = (
'id'
,'title'
, 'date_added'
, 'user'
, 'content'
, 'teaser'
)