如何在模型上添加到期日期函数? [英] how can i add an expiration date function on a model?

查看:25
本文介绍了如何在模型上添加到期日期函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个密钥验证应用程序,当该应用程序被接受时,它将在用户的个人资料上创建相同的应用程序,因此我已经做了一切,但是我一直在努力使到期日期部分有效,我希望当布尔值变为true时,日期已过期,但我不知道如何实施

i am trying to make a key verification app that when accepted it would create the same app on the user's profile, so i have done everything but i have struggled making the expiration date part, i want the expired boolean become true when the date is expired, but i have no idea on how to implement it

#models.py
    class ProductKey(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE, 
        unique=False)
        key = models.CharField(max_length=14)
        valid_from = models.DateTimeField(default=timezone.now)
        valid_to = models.DateTimeField()
        expired = models.BooleanField(default=False)

推荐答案

为此添加数据库字段.您将引入数据重复:如果您稍后设置 valid_to ,则也将必须更新 expred ,因此逻辑将带来额外的挑战.

Please do not add a database field for this. You will introduce data duplication: if you later set the valid_to, you will have to update expred as well, so the logic would introduce extra challenges.

您可以注释您的 ProductKey 模型,从而使由此产生的对象具有 expired expired 的属性:

You can annotate your ProductKey model, such that objects that arise from this have an attribute expired:

from django.db.models import BooleanField, ExpressionWrapper, Q
from django.db.models.functions import Now

ProductKey.objects.annotate(
    expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
)

然后可以对该属性进行过滤.例如,您可以检索已过期的 ProductKey :

You can then filter on that property. For example you can retrieve the ProductKeys that are expired with:

ProductKey.objects.annotate(
    expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
).filter(expired=True)

如果您经常需要此功能,则可以在管理器中对此进行注释,例如:

If you need this often, you can annotate this in the manager, like:

class ExpiredManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().annotate(
            expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
        )

class ProductKey(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, 
    unique=False)
    key = models.CharField(max_length=14)
    valid_from = models.DateTimeField(default=timezone.now)
    valid_to = models.DateTimeField()

    objects = ExpiredManager()

这篇关于如何在模型上添加到期日期函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆