我正在编写一个rest API。这是我的观点:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text {
if let floatingLabelTextField = textField as? SkyFloatingLabelTextField {
if(text.characters.count < 3 || !text.containsString("@")) {
floatingLabelTextField.errorMessage = "Invalid email"
}
else {
// The error message will only disappear when we reset it to nil or empty string
floatingLabelTextField.errorMessage = ""
}
}
}
return true
}
这是它的模型:
class OrderDeleteAPIView(generics.RetrieveDestroyAPIView):
queryset = Order.objects.all()
serializer_class = OrderDeleteSerializer
# permission_classes = (OwnerCanManageOrReadOnly,)
lookup_field = 'id'
和
class Order(models.Model):
product = models.ForeignKey(Product)
customer = models.ForeignKey(Customer, null=True)WAITING = 'WA'
PREPARATION = 'PR'
READY = 'RD'
DELIVERED = 'DV'
STATUS_CHOICES = (
(WAITING, 'waiting'),
(PREPARATION, 'preparation'),
(READY, 'ready'),
(DELIVERED, 'delivered'),
)
status = models.CharField(
max_length=2,
choices=STATUS_CHOICES,
default=WAITING,
)
这是它的序列化器:
class Customer(models.Model):
name = models.CharField(max_length=40)
customer_email = models.EmailField()
def __str__(self):
return self.name
如果我想要删除对象(订单),只有当状态字段为“等待”时,我该怎么办? ?
答案 0 :(得分:0)
您可以在destroy
中实施一些检查,并在遇到约束 的情况下返回错误消息作为响应:
class OrderDeleteAPIView(generics.RetrieveDestroyAPIView):
queryset = Order.objects.all()
serializer_class = OrderDeleteSerializer
# permission_classes = (OwnerCanManageOrReadOnly,)
lookup_field = 'id'
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
if instance.status != Order.WAITING:
return JsonResponse(
status=412,
data={'status':'false',
'message': 'status should be WAITING'}
)
super(OrderDeleteAPIView, self).destroy(request, *args, **kwargs)
当然,您可以返回任何类型的答案(不是本身 JSON响应,状态也不是412)。通常,HTTP状态代码412表示412 Precondion failed。