我正在设置期刊订阅购物车,并希望用户能够根据与当前日期的距离订购订阅。
每个订阅包含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年”会在过去找Subscription
个start_date
,但过去最近的。{/ p>
“从下一个开始的订单1年”将返回Subscription
,其中start_date
最接近当前日期。
我如何在视图中实现这种逻辑?
答案 0 :(得分:1)
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")
答案 1 :(得分:0)
我认为最好将其放在forms
逻辑中而不是views
中。
我认为还有一个Issue
模型,如下所示:
class Issue(models.Model):
issue_date = models.DateField()
....
保存Subscription
后,您的save()
应该执行以下操作:
from models import Subscription
from django import forms
class SubscriptionForm(forms.ModelForm):
def save(self, commit=True):
instance = super(SubscriptionForm, self).save(commit=False)
if instance.start_from_next: # You should add a start_from_next boolean field to know if user wants to start from previous or next issue
the_issue = Issue.objects.filter(issue_date__gt=date.today()).order_by("start_date")[0]
else:
the_issue = Issue.objects.filter(issue_date__lt=date.today()).order_by("-start_date")[0]
instance.start_date = the_issue.start_date
if commit:
instance.save()
return instance
class Meta:
model = Subscription