【发布时间】:2020-10-18 16:03:45
【问题描述】:
我有一个订单模型,我想验证每个订单的数量不超过所需产品的实际产品数量,我想通过 Django 验证器来实现这一点..
每个应用程序的所有验证器都保存在一个名为 valditaors.py 的单独文件中,现在问题是如何将 Order 模型通过外键字段引用的产品模型对象传递给指定的验证器数量字段来验证所需产品是否有足够的数量,而不是单独传递实际数量字段值。
我的订单模型:
class Order(models.Model):
product = models.ForeignKey('Product', on_delete=models.RESTRICT, related_name='orders') # I want to pass this product to the same validator((check_quantity_available)) specified on the next field.
quantity = models.PositiveIntegerField(validators=[MinValueValidator(1), check_quantity_available]) # in addition to this field value as well
我的验证者:
def check_quantity_available(value):
pass # how to get the product instance here throuh the Order model so I may check if it has enough quantity or not
【问题讨论】:
-
如果这是用于电子商务/购物车,那么这是错误的方法。您想保留库存,而不是检查是否有足够的库存来避免竞争条件。
标签: python-3.x django django-models