如何使用 django rest 框架在嵌套序列化器对象中创建三个表

how to create three tables in nested-serializer objects using django rest framework

我正在尝试在 django rest 框架中创建一个三模型嵌套对象

models.py

class Project(models.Model):
    project_id = models.AutoField(primary_key=True, unique=True)
    project_name = models.CharField(max_length=100)

class ProjectSite(models.Model):
    site_id = models.AutoField(primary_key=True, unique=True)
    site_name = models.CharField(max_length=200,name='project_site_name')
    project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True, 
    related_name="projectid")

class Assignment(models.Model):
    assignment_id = models.AutoField(primary_key=True)
    assignment_name = models.CharField(max_length=150)
    site_id = models.ForeignKey(ProjectSite,related_name="projectsiteidkey", on_delete=models.CASCADE)
    assigned_to_id = models.ForeignKey('auth.User',related_name="assignedtoidfkey",on_delete=models.CASCADE)

serializer.py

class ProjectSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Project
        fields = '__all__'
class ProjectSiteSerializer(serializers.ModelSerializer):
  
    class Meta:
        model = ProjectSite
        fields = '__all__'

class AssignedUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Assignment
        fields = '__all__'

class CreateNewProjetSerial(serializers.ModelSerializer):
    site_name = ProjectSiteSerializer(many=True)
    assigned_to_id = AssignedUserSerializer(many=True)
    class Meta:
        model = Project
        fields = ['site_name','project_name','assigned_to_id']
   
    def create(self, validated_data):
        site_name = validated_data.pop('site_name')
        assigned_to_id = validated_data.pop('assigned_to_id')
        
        projects = Project.objects.create(**validated_data)
  
        for i in site_name:
            ProjectSite.objects.create(site_name=projects, **i)
            
            
        for j in assigned_to_id:    
            Assignment.objects.create(assigned_to_id=projects, **j)
  
        return projects 

view.py

class MultieCreateAPIView(generics.CreateAPIView):
  queryset = Project.objects.all()
  serializer_class = CreateNewProjetSerial

我想post一个JSON这样的对象


 
{
"site_name": [{"site_name": "site1"}, {"site_name": "site2"}],
"project_name": "test_project",
"assigned_to_id": [{"assigned_to_id":2}, {"assigned_to_id":3}]
}


当我尝试 post 时,出现错误“无法分配“<项目:test_project>”:“Assignment.assigned_to_id”必须是“用户”实例”。 感谢您提前帮助我。

首先,您不需要设置 primary_key 字段,因为 django 会为您完成。所以你最好分别从3个模型中删除project_idsite_idassignment_id字段。 CreateNewProjetSerial 中存在一些错误。 site_nameassigned_to_id 字段应为 read_only,如果您无法使用相关对象上传,则需要额外的字段来接收您的负载。

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)

    class Meta:
        model = Project
        fields = ['site_name','project_name','assigned_to_id', 'site_names', 'user_ids']
   
    def create(self, validated_data):
        site_names = validated_data.pop('site_names')
        user_ids = validated_data.pop('user_ids')
        
        new_project = Project.objects.create(**validated_data)
  
        for site_name in site_names:
            new_project_site = ProjectSite.objects.create(project_id=new_project, site_name=site_name)            
            
            for user_id in user_ids:    
                Assignment.objects.create(assigned_to_id__id=user_id, site_id=new_project_site)
  
        return new_project

并且在前端,请像下面这样上传。

{
    "site_names": ["site1", "site2"],
    "project_name": "test_project",
    "user_ids": [2, 3]
}