使用DRF将行添加到m2m表

时间:2018-09-22 19:57:07

标签: python django django-rest-framework

我的模型中具有以下表示形式。py

class Agent(models.Model):
    name = models.CharField(max_length=200)
    user = models.OneToOneField(SampignanUser, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Project(models.Model):
    client = models.ForeignKey(Client, related_name='projects', on_delete=models.CASCADE)
    agent = models.ManyToManyField(Agent)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

我想创建一个其他端点,在其中我可以让一个代理申请特定项目(即-在Project-agents表中创建一行)。有什么特别的方法可以做到吗?现在,我已经尝试了以下方法

urls.py

urlpatterns = [
    path('projects/<int:project_id>/apply/', views.project_application, name='apply')
]

views.py

@api_view(['GET','POST'])
def project_application(request, project_id):

    if request.method == 'GET':
        serializer = ProjectApplicationSerializer()
        // show an empty form to the user
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = ProjectApplicationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的serializers.py

class ProjectApplicationSerializer(serializers.ListSerializer):

    agent = AgentSerializer
    project = ProjectSerializer

但是它似乎不起作用,我从Django得到以下错误

`child` is a required argument.

1 个答案:

答案 0 :(得分:0)

我可以建议您使用public class FileListAdapter extends PrimeAdapter { @Nullable @Override public PrimeViewHolder<?> makeViewHolder(@Nullable Class<?> dataHolderClass) { if (dataHolderClass == PdfDataHolder.class) { return new PdfViewHolder(this); } else if (dataHolderClass == ImageDataHolder.class) { return new ImageViewHolder(this); } else { return null; } } } 。因此,它看起来像:

serializers.ModelSierializer

在这里,class ProjectModelSerializer(serializers.ModelSerializer): class Meta: model = Project fields = [..., 'agent',....] # you can use exclude also def to_representation(self, instance): self.fields['agent'] = AgentSerializer(many=True) return super().to_representation(instance) 自动处理多对多字段。此外,在显示结果时,您可以在序列化器的ModelSerializer方法中将agent作为对象返回来进行定义。因此,它不仅会返回数组中代理的ID,而且还会返回定义为to_representation(self, instance)的其他信息。如果要创建许多项目,则应在AgentSerializermany=True)中使用ProjectModelSerializer关键字,请求主体将如下更改:

ProjectModelSerializer(data=request.data, many=True)