Django使用timedelta过滤temp中的结果

2024-06-02 10:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设置一个期刊订阅购物车,希望用户能够订购基于距离当前日期的订阅。在

每个订阅包含3期。我想给人们一个选择,从现在的一期开始订购1年,或者从下一期开始订购1年。在

我的模型相当简单:

class Subscription(models.Model):
  start_date = models.DateField(max_length=10)
  end_date = models.DateField(max_length=10)
  date = models.DateTimeField(auto_now_add=True, blank=True)
  def __unicode__(self):
      return unicode(self.start_date)

理想情况下,“从当前开始的1年订单”将查找过去带有start_dateSubscription,但最近的在过去。在

“order1 year start with next”将返回一个Subscription,其中start_date与将来的当前日期最接近。在

如何在视图中实现这种逻辑?在


Tags: 用户模型selftrue距离datemodelsunicode
2条回答

在视图.py在

class NextSubscription(View):
    def get(self, request):
        try:
            return Subscription.objects.filter(start_date__gt=date.today()).order_by("start_date")[0]
        except IndexError:
            raise Exception("No Next Subscription Found")

class CurrentSubscription(View):
    def get(self, request):
        try:
            return Subscription.objects.filter(start_date__lt=date.today()).order_by("-start_date")[0]
        except IndexError:
            raise Exception("No Current Subscription Found")

我认为最好把它放在你的forms逻辑中,而不是views。 我想还有一个Issue模型,类似于:

class Issue(models.Model):
    issue_date = models.DateField()
    ....

在保存Subscription时,您的save()应该执行以下操作:

在表单.py在

^{pr2}$

相关问题 更多 >