Home > Blockchain >  DRF create method raise 'null value in column "project_id_id" violates not-null const
DRF create method raise 'null value in column "project_id_id" violates not-null const

Time:06-16

I got an integrity error while assigning new sites to the existing project id's I followed the same solution from this answer Please find there models & serializers & views while trying with below script I got IntegrityError: null value in column "project_id" violates not-null constraint DETAIL: Failing row contains (18, , null, 2022-06-14 16:43:12.319679 00, 2022-06-14 16:43:12.319679 00, t, 3, 3, null).

class CreateNewProjetSerial(serializers.ModelSerializer):
    site_name = ProjectSiteSerializer(many=True, read_only = True)
    assigned_to_id = AssignedUserSerializer(many=True, read_only = True)
    site_names = serializers.ListField(
        child = serializers.CharField(), write_only = True)
    user_ids = serializers.ListField(
        child = serializers.IntegerField(), write_only = True)
    project_ids = serializers.ListField(
        child = serializers.IntegerField(), write_only=True
    )

    class Meta:
        model = Project
        fields = ['site_name','project_name','assigned_to_id', 'project_ids','site_names', 'user_ids']
   
    def create(self, validated_data):
        site_names = validated_data.pop('site_names')
        user_ids = validated_data.pop('user_ids')
        project_ids = validated_data.pop('project_ids')
        new_project = ProjectSite.objects.create(**validated_data)
  
        for project in project_ids :
            new_project_site = Project.objects.create(project_id_id=project, **validated_data)            
            
            for user_id in user_ids:    
                Assignment.objects.create(assigned_to_id__id=user_id, site_id=new_project_site)
  
        return new_project
class Project(models.Model):
    project_id = models.AutoField(primary_key=True, unique=True)
    project_name = models.CharField(max_length=100)


json object for post 
{
    "site_names": ["site1106", "site2106"],
    "user_ids": [1],
    "project_ids": [16]
}

CodePudding user response:

In you json object, you use the key as "project_id" and in create method you use the key as "project_ids".

CodePudding user response:

I think the code for saving part is wrong. It should be project_id, not the project_id_id

...
for project in project_ids :
    new_project_site = Project.objects.create(project_id=project, **validated_data)

...
  • Related