类别归档不要以api创建形式出现

时间:2019-05-13 15:02:31

标签: django django-rest-framework

我正在使用django rest框架,但我的问题是类别和标签fileds没有出现在api创建表单或更新表单中,我正在使用ModelSerializer,如何我解决了吗?

serializers.py

# -*- coding: utf-8 -*-
from django.utils.safestring import mark_safe
from markdown import markdown
from users.models import *
from rest_framework import serializers
from articles.models import *


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ouser
        fields = ('id', 'username', 'first_name', 'last_name', 'avatar')


class TagModelSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Tag
        exclude = ['updated_at', 'created_at']
        extra_kwargs = {
            'url': {'view_name': 'tag-api', 'lookup_field': 'slug'},
        }


class CategoryModelSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Category
        exclude = ['updated_at', 'created_at']
        extra_kwargs = {
            'url': {'view_name': 'category-api', 'lookup_field': 'slug'},
        }


class ArticleModelSerializer(serializers.ModelSerializer):
    author = UserModelSerializer(read_only=True)
    content_as_markdown = serializers.SerializerMethodField()
    date = serializers.SerializerMethodField()
    url = serializers.HyperlinkedIdentityField(
        view_name='article-api',
        lookup_field='slug'
    )
    category = CategoryModelSerializer(read_only=True)
    tags = TagModelSerializer(read_only=True, many=True)

    class Meta:
        model = Article
        exclude = ['updated_at', 'created_at']

    def get_date(self, obj):
        return obj.published_at.strftime("%b %d, %Y")

    def get_content_as_markdown(self, obj):
        return mark_safe(markdown(obj.content, safe_mode='escape'))

1 个答案:

答案 0 :(得分:0)

这是因为您在它们上设置了read_only=True。从字面上看,这会导致您所拥有的-在任何创建或更新调用中都不存在字段。