如何通过WorkOrder返回评论列表?

时间:2017-11-28 12:07:26

标签: python django

我有这样的情况:

我有一个WorkOrder类:

class WorkOrder(models.Model):
    workorder_num = models.CharField(max_length=64, help_text="workorder number")
    name = models.CharField(max_length=32, help_text="name")
    content = models.TextField(help_text="content")

我还有一个WorkOrderComment类:

class WorkOrderComment(models.Model):
    """
    comment 
    """
    workorder = models.ForeignKey(WorkOrder, help_text="belong to which order"  )  
    comment_user = models.OneToOneField(User, help_text="comment user")
    content = models.CharField(max_length=256, help_text="content")

所以,有一个要求,我想列出工作顺序的注释,所以我写了序列化器和视图:

串行器:

class WorkOrderCommentSerializer(ModelSerializer):
    class Meta:
        model = WorkOrderComment
        fields = "__all__"

视图:

class WorkOrderCommentListAPIView(ListAPIView):
    serializer_class = WorkOrderCommentSerializer
    permission_classes = []
    queryset = WorkOrderComment.objects.filter()

但如果我列出了工作订单评论,你知道它会列出所有评论,没有组织。

我想通过工作订单来评论如何处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

您可以使用nested-relationships来执行此操作。

您不需要WorkOrderCommentListAPIView

您可以在WorkOrderCommentSerializer

class WorkOrderCommentSerializer(ModelSerializer):

    comments = WorkOrderCommentSerializer(many=True, read_only=True)
    class Meta:
        model = WorkOrderComment
        fields = "__all__" 

然后访问WorkOrderCommentSerializer,你可以得到你想要的东西。