Django rest框架从API Create表单中删除字段

时间:2018-09-22 12:39:14

标签: django python-3.x api django-rest-framework

我有一个模型和与此模型有关的视图集, 这是我的代码:

class EMAILTemplate(models.Model):
    """ Message SMS Template """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    body = models.TextField()
    tokens = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        self.tokens = ",".join(re.findall(r'{{\s*(.*?)\s*}}', self.body))
        super().save(*args, **kwargs)

我不希望字段标记在Django rest框架的create表单中创建或编辑表单,因为如您所见,它将从body字段中提取。 但我想在单个模型或模型列表中查看此字段。

这是我的ModelSerializer:

class EmailTemplateSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = EMAILTemplate
        fields = ('name', 'body', 'user', 'tokens')

2 个答案:

答案 0 :(得分:1)

您可以将tokens指定为只读字段:

class EmailTemplateSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = EMAILTemplate
        fields = ('name', 'body', 'user', 'tokens')
        read_only_fields = ('tokens',)

答案 1 :(得分:1)

您可以覆盖当前的to_representation方法

class EmailTemplateSerializer(serializers.HyperlinkedModelSerializer):

    def to_representation(self, obj):
        try:
            if self.context['view'].action in ['list', 'detail']:
                # get the original representation
                ret = super(serializers.HyperlinkedModelSerializer, self).to_representation(obj)
                # remove 'tokens' field
                ret.pop('tokens')
                return ret
        except KeyError:
            return super(serializers.HyperlinkedModelSerializer, self).to_representation(obj)
        return super(serializers.HyperlinkedModelSerializer, self).to_representation(obj)