如何立即将数据保存到数据库后,我该怎么做?

时间:2017-11-30 11:25:45

标签: python django django-rest-framework

我有一个WorkOrderCreateAPIView和WorkOrderCreateSerializer:

# views
class WorkOrderCreateAPIView(CreateAPIView):
    serializer_class = WorkOrderCreateSerializer
    permission_classes = []
    queryset = WorkOrder.objects.all()

# serializers
class WorkOrderCreateSerializer(ModelSerializer):
    """
    Create the work order
    """
    class Meta:
        model = WorkOrder
        exclude = ("workorder_num","to_group","user", "workorder_status")

    def create(self, validated_data):

        user = getUserFormSerializer(self)
        to_group = Group.objects.filter(name=ADMIN_GROUP_CHOICES.售后组).first()

        return WorkOrder.objects.create(
            user=user,
            workorder_num = generateWorkorderNum(userid=user.id),
            to_group=to_group,
            workorder_status = WORKORDER_STATUS_CHOICES.已提交,
            **validated_data,
        )

我可以访问WorkOrderCreateAPIView来创建工单,但是,我想在立即保存WorkOrder实例后做一些事情。

您可以在create(self, validated_data)方法中看到最后一行是return WorkOrder.objects.create(xxx),它不是保存数据,因此,如何知道序列化程序或视图何时保存数据?在将数据保存到数据库之后,我想立即做一些其他事情,例如发送电子邮件。

1 个答案:

答案 0 :(得分:0)

您可以使用signals,但我认为这不是唯一的方法。