Django Rest Framework - 显示预填充的slug字段

时间:2016-04-28 14:23:00

标签: django django-rest-framework

我有一个slug字段用于我希望在对象表示中返回的模型,但 NOT 作为可浏览API中表单输入的一部分。它由模型上的slugify方法生成。

当我使用ModelSerializer将其添加到Meta并尝试在可浏览的api表单中添加新字段时,将read_only_fields=('slug',)标记为只读"This field is required."

参考序列化器如下:

class CategorySerializer(serializers.HyperlinkedModelSerializer):
    slug = serializers.SlugField(read_only=True, required=False)

    def to_representation(self, obj):
        self.fields['children'] = CategorySerializer(obj, many=True, read_only=True)
        return super(CategorySerializer, self).to_representation(obj)

    class Meta:
        model = Category
        fields = ('pk', 'url', 'title', 'slug', 'parent', 'children', 'active', 'icon')
        read_only_fields = ('children','slug',)

在表示中显示字段的简单解决方案是什么,而不是上面给出的可浏览api表单?

供参考,这是我的模型:

@python_2_unicode_compatible
class CategoryBase(mptt_models.MPTTModel):
    parent = mptt_fields.TreeForeignKey( 'self', blank=True, null=True, related_name='children', verbose_name=_('parent'))
    title = models.CharField(max_length=100, verbose_name=_('name'))
    slug = models.SlugField(verbose_name=_('slug'), null=True)
    active = models.BooleanField(default=True, verbose_name=_('active'))

    objects = CategoryManager()
    tree = TreeManager()

    def save(self, *args, **kwargs):
        """
        While you can activate an item without activating its descendants,
        It doesn't make sense that you can deactivate an item and have its
        decendants remain active.
        """
        if not self.slug:
            self.slug = slugify(self.title)

        super(CategoryBase, self).save(*args, **kwargs)

        if not self.active:
            for item in self.get_descendants():
                if item.active != self.active:
                    item.active = self.active
                    item.save()

    def __str__(self):
        ancestors = self.get_ancestors()
        return ' > '.join([force_text(i.title) for i in ancestors] + [self.title, ])

    class Meta:
        abstract = True
        unique_together = ('parent', 'slug')
        ordering = ('tree_id', 'lft')

    class MPTTMeta:
        order_insertion_by = 'title'


class Category(CategoryBase):
    icon = IconField(null=True, blank=True)
    order = models.IntegerField(default=0)

    @property
    def short_title(self):
        return self.title

    def get_absolute_url(self):
        """Return a path"""
        from django.core.urlresolvers import NoReverseMatch
        try:
            prefix = reverse('categories_tree_list')
        except NoReverseMatch:
            prefix = '/'
        ancestors = list(self.get_ancestors()) + [self, ]
        return prefix + '/'.join([force_text(i.slug) for i in ancestors]) + '/'

    def save(self, *args, **kwargs):
        super(Category, self).save(*args, **kwargs)

    class Meta(CategoryBase.Meta):
        verbose_name = _('category')
        verbose_name_plural = _('categories')

0 个答案:

没有答案