在Django Rest Framework中保存序列化程序时将None传递给外键

时间:2018-05-29 06:52:04

标签: django null django-rest-framework foreign-keys

这是标题的模型,

class Header(models.Model):
    id = models.AutoField(primary_key=True)
    features = models.ForeignKey(Project, null=True, blank=True, related_name= 'features')
    def __str__(self):
        return str(self.name)

这是Project的模型(Header中的功能的外键):

class Project(models.Model):
    id = models.AutoField(primary_key=True)
    project_info = models.OneToOneField(ProjectInfo, related_name='project_info')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    dataset_associated = models.ForeignKey(Dataset)  
    ratio_test_training = models.IntegerField()
    random_seed = models.IntegerField(blank=True, null=True) 
    url = models.URLField(blank=True, null=True)
    def __str__(self):
        return str(self.project_info.name)

而且,当我尝试通过将None传递给功能来保存Header序列化程序时,它会显示错误:

{features: ["This field may not be null."]}

即使我将其属性设置为null = True。

这是Header的序列化程序:

class HeaderSerializer(serializers.ModelSerializer):
                features = ProjectSerializer()
                class Meta:
                        model = models.Header
                        fields = ('id', 'features') 
                def create(self, validated_data):
                        features_data = validated_data.pop("features")
                        if(features_data):
                                      features = models.Project.objects.get(pk =
                        (features_data.get("id")))
                        else:
                               features = None
                        obj=models.Header.objects.create(features = features)
                        obj.save()
                        return obj

这是views.py,

中的代码
@api_view(['GET', 'POST', 'DELETE'])
def header_detail_pk(request):
    if request.method == 'POST':
        features = request.POST.get('features')
        if(features):
            features = project_serializer.data
            print("Not none")
        else:
            features = None
        serializer = HeaderSerializer('features':features)
        if serializer.is_valid():
            serializer.save(features= features)
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是Project序列化程序:

class ProjectSerializer(serializers.ModelSerializer):
        project_info = ProjectInfoSerializer()
        dataset_associated = DatasetSerializer()
        class Meta:
                model = models.Project
                fields = ('id', 'project_info','created_at', 'updated_at', 'dataset_associated', 'ratio_test_training', 'random_seed', 'url')
        def create(self, validated_data):
                project_info_data = validated_data.pop("project_info")
                dataset_associated_data = validated_data.pop("dataset_associated")
                project_info_id = project_info_data.get("id")
                dataset_associated_id = dataset_associated_data.get("dataset_id")
                project_info = models.ProjectInfo.objects.get(pk=project_info_id)
                dataset_associated = models.Dataset.objects.get(dataset_id=dataset_associated_id)
                obj = models.Project.objects.create(url = validated_data.get("url") ,ratio_test_training=validated_data.get("ratio_test_training"), random_seed=validated_data.get("random_seed"), project_info=project_info, dataset_associated=dataset_associated)
                obj.save()
                return obj

1 个答案:

答案 0 :(得分:0)

第一个变种

 class HeaderSerializer(serializers.ModelSerializer):
                class Meta:
                        model = models.Header

#Second variant

class HeaderSerializer(serializers.ModelSerializer):
                features = ProjectSerializer(allow_null=True)
                class Meta:
                        model = models.Header
                        fields = ('id', 'features') 
                def create(self, validated_data):
                        features_data = validated_data.pop("features")
                        if(features_data):
                                      features = models.Project.objects.get(pk =
                        (features_data.get("id")))
                        else:
                               features = None
                        obj=models.Header.objects.create(features = features)
                        obj.save()
                        return obj

ProjectSerializer中的参数可以更改取决于您的DRF版本,我认为您不需要覆盖create方法