Django错误:您无法将dateOfBirth(不可为空的字段)设置为None

时间:2016-08-11 17:22:24

标签: django mongodb

我正在使用Django-nonrel和mongodb。我有以下型号:

class Patient(models.Model):
    firstName = models.CharField(max_length=100, blank=True, default='')
    lastName = models.CharField(max_length=100, blank=True, default='')
    occupation = models.CharField(max_length=100, blank=True, default='')
    gender = models.CharField(max_length=50, blank=True, default='')
    dateOfBirth = models.DateField()
    address = AddressField();

我也是这个模型的序列化器:

class PatientSerializer(serializers.Serializer):
    firstName = serializers.CharField()
    lastName = serializers.CharField()
    occupation = serializers.CharField()
    gender = serializers.CharField()
    dateOfBirth = serializers.DateField()
    address = AddressField();

    def create(self, validated_data):
        """
        Create and return a new patient
        """
        return Patient.objects.create()(**validated_data)

最后,我正在使用视图:

def patient_list(request):
    # Create a new patient 
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = PatientSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)

我发送此JSON请求:

{"firstName":"Yasir","lastName":"Khan","occupation":"Engieneer","gender":"male","dateOfBirth":"2016-08-09","address":"1, avenue Rosa Parks"}

当我尝试这个时,我收到一条错误,说dateOfBirth是none:

/ records /中的IntegrityError 您不能将dateOfBirth(非可空字段)设置为None!

IntegrityError at /records/
You can't set dateOfBirth (a non-nullable field) to None!

我看不出错误在哪里,正如你所看到的,dateOfBirth并不是真的。

1 个答案:

答案 0 :(得分:0)

我认为问题出现在序列化程序中的create方法中(假设您在此处发布的代码中没有拼写错误)

0.01

在您的return语句中,您没有将validated_data传递给create方法。尝试将其更改为

def create(self, validated_data):
    """
    Create and return a new patient
    """
    return Patient.objects.create()(**validated_data)

模型中的其他字段已指定默认值,因此Django仅抱怨dateOfBirth。