我有一个订单模型,它的字段状态有选择 -> 新(默认)、待处理(PDG)、已调度(DSP)、已完成(CMP)、取消(CLD)
模型.py
class Order(Address, TimeStampedUUIDModel):
status = FSMField(
max_length=25,
choices=constants.STATUS_CHOICES,
default=constants.NEW,
)
@transition(field=status, source=constants.NEW, target=constants.PDG)
def to_pending(self):
self.status = constants.PDG
@transition(field=status, source=constants.PDG, target=constants.DSP)
def to_dispatched(self):
self.status = constants.DSP
@transition(field=status, source=constants.DSP, target=constants.CMP)
def to_completed(self):
self.status = constants.CMP
@transition(
field=status,
source=[constants.NEW, constants.PDG, constants.DSP],
target=constants.CLD,
)
def to_cancel(self):
self.status = constants.CLD
序列化程序.py
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = models.Order
fields = "__all__"
read_only_fields = [--all fields except status--]
def update(self, instance, validated_data):
status = validated_data.pop("status", None)
agent = self.context['request'].user
instance = services.status_function(status, instance, agent)
return instance
在下面的服务文件中,我同时尝试创建一个订单活动对象来跟踪订单对象的变化。服务.py
def status_function(status, instance, agent):
if status is not None:
switcher = {
constants.PDG : instance.to_pending,
constants.DSP : instance.to_dispatched,
constants.CMP : instance.to_completed,
constants.CLD : instance.to_cancel
}
func = switcher.get(status, None)
try:
func()
models.OrderActivity.objects.create(
event_name=status,
order = instance,
event = f"Order {status}",
agent = agent,
time = instance.modified_at
)
except TransitionNotAllowed :
print("Exception Caught")
raise exceptions.BadRequest([{"error": "Transition not allowed"}])
return instance
常量.py
from extended_choices import Choices
## Order Status
NEW, NEW_ = "NEW", "NEW"
PDG, PDG_ = "PDG", "PENDING"
DSP, DSP_ = "DSP", "DISPATCHED"
CMP, CMP_ = "CMP", "COMPLETED"
CLD, CLD_ = "CLD", "CANCELLED"
STATUS_CHOICES = (
(NEW, NEW_),
(PDG, PDG_),
(DSP, DSP_),
(CMP, CMP_),
(CLD, CLD_),
)
我的问题是,除了 NEW -> PDG、NEW -> CLD 和 PDG -> CLD 之外的转换正在引发异常,并且还将 Order 对象的状态恢复为 NEW,这不应该发生。提前致谢 !!!!