DjangoRestFramework - 正确添加" required = false"到ModelSerializer字段?

时间:2015-10-07 20:26:07

标签: django serialization deserialization django-rest-framework

这是我的序列化器:

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('user', 'post', 'reblog',)

    def create(self, validated_data):
        post = Post(
                user =  validated_data['user'],
                post = validated_data['post'],
        )

        post.save() 

        # manually create a list of "reblog" users
        post.reblog.add(validated_data['user'])

        return post

这是我的模特:

class Post(models.Model):
    user = models.ForeignKey(User)
    post = models.CharField(max_length=400)
    reblog = models.ManyToManyField(User)

现在,我不希望我的reblog字段在数据库中永远为空(它可以是一个空列表,但不是null)。所以我没有设置" null = True"在模型领域。但是,最终用户不必提供" reblog"用户在创建帖子时(我会在create()mtehod中手动执行此操作。)

我知道这里:http://www.django-rest-framework.org/api-guide/fields/#core-arguments它说我可以添加" required = false"到一个序列化器字段,但我在序列化程序中使用的字段直接来自模型(即fields =(' reblog'))。

根据我的理解,我无法添加" required = false"我的模特因为这里: https://docs.djangoproject.com/en/1.8/ref/models/fields/它没有提及"必需"作为模型字段的参数。

话虽如此,我怎样才能得到我的" reblog"在serailzation / deserialization期间不需要ModelSerializer字段?

编辑:处理发送的帖子请求的视图是:

class post_list(APIView):
    """
    List all posts or create a new post.
    """
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = PostSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

pip freeze:

You are using pip version 6.1.1, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Django==1.8
djangorestframework==3.1.1
uWSGI==2.0.10

1 个答案:

答案 0 :(得分:1)

将参数blank=True添加到模型字段:

class Post(models.Model):
    user = models.ForeignKey(User)
    post = models.CharField(max_length=400)
    reblog = models.ManyToManyField(User, blank=True)
                                         #^^^^^^^^^^

现在,请求可能会省略该参数,但它可能永远不会是NULL值。

现在总是:

urls.py(基本上内联serializers.py):

from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
from proj.models import Post



# Serializers define the API representation.
class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('user', 'post', 'reblog',)

    def create(self, validated_data):
        post = Post(
                user =  validated_data['user'],
                post = validated_data['post'],
        )

        post.save() 

        # manually create a list of "reblog" users
        post.reblog.add(validated_data['user'])

        return post
class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'Post', PostViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

models.py

from django.contrib.auth.models import User
from django.db import models

class Post(models.Model):
    user = models.ForeignKey(User)
    post = models.CharField(max_length=400)
    reblog = models.ManyToManyField(User, blank=True,related_name='reblog_users')

现在,当我发送POST请求时:

{
    "user": 1,
    "post": "foo"
}

它返回:

{
    "user": 1,
    "post": "foo",
    "reblog": [
        1
    ]
}

pip freeze

Django==1.8.4
djangorestframework==3.2.4