【问题标题】:Django ORM - get records that are older than record's `duration` daysDjango ORM - 获取早于记录的“持续时间”天的记录
【发布时间】:2019-05-16 11:07:10
【问题描述】:

我有模型:

class Plan(models.Model):
  date = models.DateTimeField()
  duration = models.DurationField(default=30)

我想使用 ORM 获取早于 today - duration 的记录。可能吗?也许像Plan.objects.filter(date__lt='self.duration') 这样的东西存在?

【问题讨论】:

标签: django django-orm


【解决方案1】:

就像评论 F expressions 中提到的 Ivan Starostin 非常有用:

today = datetime.now()
plans = Plan.objects.filter(date__lt=today - F('duration'))

【讨论】:

    【解决方案2】:

    是的,你可以这样做:

    Plan.objects.filter(duration__lt='YYYY-MM-DD')
    

    假设我有一个已创建字段的产品模式

    class Product(models.Model):
         created = models.DateTimeField(auto_now_add=True)
         #other fields
    
    Product.objects.filter(created__lt='2019-05-15')
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多