我正在建设一个自行车租赁ap。
前端:用户选择开始日期和结束日期,并在列表视图中获取所有可用的自行车,带有类别和适当价格的自行车。
价格:价格是在两个条件下计算的。车辆和持续时间。(因为价格有持续时间板。
1-3天=145美元运动量
1-3天=145美元滑板车
4-7天=2004年运动
4-7天=2004年滑板车等
只能从前端表单中选定的日期获得持续时间,然后将其转换为天数。
我需要传递这些天作为持续时间,以获得适当的价格,并相应地在每个类别下显示在一个列表视图。
MODELS.PY
VehicleCategory类:
@property
def price(self, duration):
for item in VehiclePrice.objects.all():
If item.vehicle_category.title == self.title and (duration >= item.slab.start and duration <= item.slab.end):
return item.net_priceVIEWS.PY
类HomeView(ListView):
template_name = 'app/home.html'
def get(self, request):
if request.method == "GET":
start_date = request.GET.get('start_date')
end_date = request.GET.get('end_date')
if start_date and end_date:
start_date = datetime.strptime(start_date, "%m/%d/%Y").date()
end_date = datetime.strptime(end_date, "%m/%d/%Y").date()
duration = (end_date - start_date).days +1
vehiclecategory= VehicleCategory.objects.all()
context = {
'vehiclecategory1': vehiclecategory.filter(main_category= 'E-Cycle'),
'vehiclecategory2': vehiclecategory.filter(main_category= 'E-Scooter'),
'form':CartQuantityForm(),
'dateform': DateForm()
}
return render(request, self.template_name, context )在这里,我得到了持续时间,如何在模型方法价格参数中传递这个值,并使上面的Queryset工作?“”
发布于 2020-05-09 09:18:04
根据您给出的价格需要的信息,下列条件为真:
注意,对于@property,您不能向函数传递参数,因为您将用obj.price而不是obj.price(duration)来调用它。
这将导致以下QuerySet:
def price(self, duration):
return VehiclePrice.objects.filter(
title=self.title,
slab__start__lte=duration,
slab__end__gte=duration).first()这将返回满足此条件的第一个对象。注意,如果没有找到价格,first()将根据文档返回None。
如果要在模板中调用此方法,则必须创建一个自定义模板标签并将持续时间传递给该标记,以返回价格。
另一种选择是获取视图中的所有类别,并从中获取取决于它们的价格。
您还可以使用注释将price对象附加到您的模型中,因为以下链接可能会有所帮助:
发布于 2020-05-09 09:11:25
Views.py
template_name = 'app/home.html'
def get(self, request):
if request.method == "GET":
start_date = request.GET.get('start_date')
end_date = request.GET.get('end_date')
vehiclecategory= VehicleCategory.objects.all()
if start_date and end_date:
start_date = datetime.strptime(start_date, "%m/%d/%Y").date()
end_date = datetime.strptime(end_date, "%m/%d/%Y").date()
duration = (end_date - start_date).days +1
vehiclecategory = vehiclecategory.filter(slab__start__lte=duration, slab__end__gte=duration)
context = {
'vehiclecategory1': vehiclecategory.filter(main_category= 'E-Cycle'),
'vehiclecategory2': vehiclecategory.filter(main_category= 'E-Scooter'),
'form':CartQuantityForm(),
'dateform': DateForm()
}
return render(request, self.template_name, context )https://stackoverflow.com/questions/61693776
复制相似问题