Search code examples
djangodjango-rest-frameworkdjango-rest-viewsets

Django rest ModelViewSet serializer create fails


I have two models with following relationship:

class Library(models.Model):
    library_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30)
    ...

class Reader(models.Model):
    user = models.OneToOneField(User)
    phone = models.CharField(max_length=30)
    ...
    # A library has many readers
    which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE)

I have defined serializers as following (I am directly creating a User while creating a Reader for a specific Library):

class ReaderSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    email = serializers.CharField(source='user.email')
    password = serializers.CharField(source='user.password')

    class Meta:
        model = Reader
        #fields = '__all__'
        depth = 1
        fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library')


    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create(**user_data)
        user.set_password(user_data['password'])
        user.save()
        reader = Reader.objects.create(user=user, **validated_data)
        return reader

And I am writing a ModelViewSet as following:

class ReaderViewSet(viewsets.ModelViewSet):

serializer_class = ReaderSerializer

def get_queryset(self):

    readers = Reader.objects.filter(which_library=self.kwargs.get('library_id'))
    return readers

URL: router.register(r'readers/(?P<library_id>[0-9]+)', ReaderViewSet, base_name='readers')

my GET call is successful and I get all the readers in a specific Library.

I am doing a POST call with following JSON data:

{
    "username": "three",
    "email": "three@gmail.com",
    "password": "5647",
    "phone": "836365",
    "address": "sample6 address",
    "which_library": "2"
}

and also by removing "which_library" but both give me error:

IntegrityError at /api/readers/2/
(1048, "Column 'which_library_id' cannot be null")

What am I doing wrong?


Solution

  • Try to remove depth = 1 option. From the docs:

    The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option.

    Looks like with this option serializer reqiered object instead of id.