validated_data is Null in Nested ModelsSerializer

692 views
Skip to first unread message

CocaCola

unread,
Dec 5, 2016, 3:01:33 PM12/5/16
to Django REST framework
in django-rest-framework

I want to create and upload a post with multiple photos.
The post model and the photo model were constructed in a many-to-one relationship.

class Post(models.Model):
    content
= models.TextField()

class Photo(models.Model):
    post
= models.ForeignKey(Post)
    photo
= models.ImageField(upload_to='/images/')

I wanted two serializers to be nested,
And I wanted to use ModelSerializer.

#serializer.py
class PhotoSerializer(serializers.ModelSerializer):
   
class Meta:
        model
= Photo
        fields
= ('photo',)

class PostSerializer(serializers.ModelSerializer):
    photos
= PhotoSerializer(many=True, source='photo_set')
   
class Meta:
        model
= Post
        fields
= ('content', 'photos')
       
   
def create(self, validated_data):
        photos_data
= validated_data.pop('photo')
        post
= Post.objects.create(**validated_data)
       
for photo_data in photos_data:
           
Photo.objects.create(post=post, photo=photo_data)
       
return post


I refer to the official web page of the django REST framework.

This method was not writable.

The photos did not pass 'is_valid'.I definitely sent pictures of the correct form. The correct form was in request.data.

(Later, when I tested it with the comment model (with Charfield), the same thing happened.)

The way I found it in Google
I was using 'request.data' after 'is_valid'.

def perform_create(self, serializer):
    serializer
.save(
        photos
=self.request.data['photos']
   
)


It works in the most similar way I want.
I can then use ListCreateAPIView to get List or create new posts.

However, is_valid is not a meaningless method.
I am not satisfied with ignoring this.

Of course, I think there are many other ways I do not know.

But I think the Writable Nested ModelSerializer should also work correctly.

After encountering this problem,
I found my own solution and I contacted the owner of DRF a few hours ago in the wrong way.
(I sent a pull request unintentionally.
4 times? 5 times? .. but only one success)


I would like to talk a lot about this on the forum here.

The story of people who are having problems like me is also good.
Or the story that fixes my wrong view is also good.
(I am JUST a newbie who started python and has not been able to fill it for three months.)


Reply all
Reply to author
Forward
0 new messages