You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django如何根据DateTimeField起止时间控制优惠价展示

Django 优惠价时间自动控制实现方案

1. 修正Product模型代码

你当前的模型存在命名冲突问题:同时定义了名为duration的字段和同名方法,会导致逻辑异常,先做如下调整:

  • 删除冗余的duration字段,可根据需求选择性保留时长计算方法
  • 新增is_offer_active方法封装优惠时间判断逻辑,直接调用Django自带的时区工具避免时区误差

修改后的模型代码:

from django.db import models
from django.utils import timezone

class Product(models.Model):
    price = models.DecimalField(max_digits=6, decimal_places=2)
    offer_price = models.DecimalField(max_digits=6, decimal_places=2)
    offer_price_start_date = models.DateTimeField(blank=True, null=True)
    offer_price_end_date = models.DateTimeField(blank=True, null=True)

    # 可选保留时长计算方法,根据你的需求决定
    def duration(self):
        if self.offer_price_start_date and self.offer_price_end_date:
            return self.offer_price_end_date - self.offer_price_start_date
        return None

    # 新增优惠是否生效的判断方法
    def is_offer_active(self):
        now = timezone.now()
        # 只有同时设置了起止时间,且当前时间在区间内才返回生效
        if self.offer_price_start_date and self.offer_price_end_date:
            return self.offer_price_start_date <= now <= self.offer_price_end_date
        return False

Admin面板不需要额外修改,两个时间字段会默认展示在编辑页,可直接录入。


2. 调整视图代码

你当前的视图用Product.objects.all()返回的是所有产品的查询集,不是单个产品实例,模板无法直接调用单个产品的属性,需要调整为查询单个产品:

from django.shortcuts import render, get_object_or_404
from .models import Product

def product_detail(request, product_id):
    # 根据传入的产品ID查询单个产品,不存在则返回404
    product = get_object_or_404(Product, id=product_id)
    context = {
        'product': product 
    }
    return render(request, 'show.html', context)

同时需要修改你项目的urls.py,新增产品ID参数匹配规则,示例:

from django.urls import path
from . import views

urlpatterns = [
    path('product/<int:product_id>/', views.product_detail, name='product_detail'),
]

如果是产品列表页,不需要修改查询逻辑,直接在模板循环时调用判断方法即可。


3. 修改模板判断逻辑

把原来判断duration的逻辑换成判断优惠是否生效的方法即可:

{% if product.is_offer_active %}
<a>    
  Before Price ${{ product.price }}             
</a>                                            
<a> 
    Now ${{ product.offer_price }}            
</a>  
{% endif %}

注意事项

请确保你的settings.py中USE_TZ = True,保证时间判断符合你设置的时区。

内容的提问来源于stack exchange,提问作者rasel120

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:45:02