当blank = True时,Django在多对多字段上休息“需要此字段”

时间:2019-07-06 12:19:40

标签: django django-rest-framework

我有一个我想通过django-rest-api UI制作的对象。 这个对象有一个包含许多其他对象的字段。

即使该字段为空,但param设置为True,我仍然收到“需要此字段”的响应。

class Post(models.Model):
    title = models.CharField(max_length=100)
    slug = models.CharField(max_length=200, null=True)
    description = models.CharField(max_length=200, null=True)
    content = HTMLField('Content', null=True)
    black_listed = models.ManyToManyField('profile_app.Profile', related_name='black_listed_posts', blank=True)
    score = models.PositiveIntegerField(null=True, default=0, validators=[MaxValueValidator(100)])

serializers.py:

class PostSerializer(serializers.HyperlinkedModelSerializer):
    black_listed = ProfileSerializer(many=True)
    read_only = ('id',)

    def create(self, validated_data):
        self.black_listed = []

    class Meta:
        model = Post
        fields = ('id', 'title', 'slug', 'description',
                  'content',
                  'black_listed', 'score')

views.py:

class PostViewSet(ModelViewSet):
    serializer_class = PostSerializer
    queryset = Post.objects.all()
    lookup_field = "slug"

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.black_listed = []
        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)

如您所见,我尝试在序列化程序和视图集上覆盖create()方法,但这没有用,仍然给我black_list字段的要求。

enter image description here

我期望如果数据库中不需要该字段,那么序列化程序可以在创建时将其设置为“无”

我在这里想念什么?

编辑:

ProfileSerializer:

class ProfileSerializer(serializers.ModelSerializer):
    interests = InterestSerializer(read_only=True, many=True)

    class Meta:
        model = Profile
        fields = ('slug', 'user_id', 'image', 'role', 'work_at', 'interests')

1 个答案:

答案 0 :(得分:1)

您应该在序列化程序声明中提供required=False参数:

CamlQuery query = new CamlQuery();
query.ViewXml = "<View Scope='RecursiveAll'><RowLimit>50</RowLimit></View>";

List<ListItem> items = new List<ListItem>();
    do
      {
       ListItemCollection listItemCollection = lst.GetItems(query);
       ctx.Load(listItemCollection);
       ctx.ExecuteQuery();

       items.AddRange(listItemCollection);
       foreach (var item in items)
       {
          try
           {
            var file = ctx.Web.GetFileByServerRelativeUrl(item.FieldValues["FileRef"].ToString());
            ctx.Load(file);
            ctx.Load(file.Versions);
            ctx.ExecuteQuery();

如果您希望能够为此字段发布空值,则还可以添加allow_null=True