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

如何在Django models中通过模型方法设置布尔字段is_new的值为True

问题修复方案

错误点说明

  • 语法错误:Python return 语句后不支持直接跟赋值表达式,return self.is_new=True 属于非法写法,赋值和返回需要拆分操作
  • 逻辑错误:原有判断条件拿创建时间和「创建时间减30天」对比,判断恒成立,完全没有用到当前时间,不符合「创建时间距今不超过30天」的需求
  • 调用错误:timedelta 是datetime模块的内置类,不能通过DateTimeField实例self.created_date调用
  • 字段笔误:created_date字段的参数名是auto_now_add,你漏写了字母o写成aut_now_add,会导致迁移时报错

修正后代码

from datetime import datetime, timedelta
from django.db import models
# 若项目开启USE_TZ = True时区配置,额外导入 timezone 替换 datetime.now
# from django.utils import timezone

class Product(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()
    price = models.IntegerField()
    picture = models.ImageField(upload_to='picture/')
    is_popular = models.BooleanField()
    is_cart = models.BooleanField()
    is_new = models.BooleanField(default=False)
    # 修正参数名笔误
    created_date = models.DateTimeField(auto_now_add=True)
    
    def new_arrival(self):
        # 计算当前时间往前推30天的时间点,开启时区则替换为 timezone.now()
        thirty_days_ago = datetime.now() - timedelta(days=30)
        # 先赋值再返回,符合Python语法要求
        self.is_new = self.created_date >= thirty_days_ago
        return self.is_new

可选优化建议

如果不需要持久化存储is_new字段(每次调用动态计算即可),可以把is_new改为只读属性,不用存库减少数据冗余:

@property
def is_new(self):
    thirty_days_ago = datetime.now() - timedelta(days=30)
    return self.created_date >= thirty_days_ago

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:06:05