Reputation: 3728
I have an object I would like to be able to make via django-rest-api UI. This object has a manytomany field that holds other objects on it.
Even though that field is blank param is set to True, I get a response that "this field is requiered".
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)
As you can see, i tried overriding the create()
method on both serializer and viewset, but that didnt work and still gave me that the black_list field is requiered.
What i expected that if the field is not required in the db, then the serializer can set it to None on the creation
what am i missing here?
EDIT:
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')
Upvotes: 0
Views: 93
Reputation: 5968
You should provide the required=False
argument in your serializer declaration:
class PostSerializer(...):
black_listed = ProfileSerializer(many=True, required=False)
# __________________________________________^
If you want to be able to post null values for this field, you may also add allow_null=True
.
Upvotes: 1