django 如何实现取消订单的折扣码重用?

hsvhsicv  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(105)

我有一个Django项目来实现折扣码。模型如下:

class CouponCode(models.Model):
    max_usage = models.PositiveSmallIntegerField()
    max_usage_per_user = models.PositiveSmallIntegerField(default=1)
    code = CharField(max_length=10, unique=True)
    discount_percent = models.PositiveSmallIntegerField(default=0, validators=MaxValueValidator(100)])
    max_discount_amount = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)
    start_date = models.DateTimeField(null=True, blank=True)
    end_date = models.DateTimeField(null=True, blank=True)
    minimum_price = models.PositiveBigIntegerField(default=0)

class UsedCode(models.Model):
    customer = models.PositiveBigIntegerField(verbose_name='customer id')
    coupon = models.ForeignKey(CouponCode, on_delete=models.PROTECT)
    order_id = models.PositiveIntegerField()

    @classmethod
    def has_reached_max_usage_for_user(cls, coupon, user):
        usages = cls.objects.filter(coupon=coupon, customer=user).count()
        if usages < coupon.max_usage_per_user:
            return False
        return True

    @classmethod
    def has_reached_max_usage(cls, coupon):
        usages = cls.objects.filter(coupon=coupon).count()
        if usages < coupon.max_usage:
            return False
        return True

字符串
每次使用优惠券代码创建订单时,都会创建UsedCode对象。我想实现一个功能,如果订单被取消,优惠券代码可以重复使用。我宁愿不删除对象,这样我就可以跟踪数据。

i1icjdpr

i1icjdpr1#

如果您不想删除对象,您可以添加额外的文件,如:

class UsedCode(models.Model):
    customer = models.PositiveBigIntegerField(verbose_name='customer id')
    coupon = models.ForeignKey(CouponCode, on_delete=models.PROTECT)
    order_id = models.PositiveIntegerField()
    reusable = models.BooleanField(default=False)

字符串
如果订单取消,则将可重用设置为True
然后统计没有取消的订单

usages = cls.objects.filter(coupon=coupon, customer=user , reusable=False).count()

相关问题