【问题标题】:Django filter based on ForeignKey model field基于 ForeignKey 模型字段的 Django 过滤器
【发布时间】:2021-07-27 05:04:13
【问题描述】:

我正在尝试消除条码模型中多余的字段。不需要条形码的mostrecentscantime,因为我可以参考mostrecentscan.time

class Scan(models.Model):
    time=DateTimeField(default=timezone.now)
    barcode=ForeignKey('Barcode',on_delete=models.CASCADE,related_name='scans')
    location=ForeignKey(Location,on_delete=models.CASCADE)
    
class Barcode(models.Model):
    barcode = CharField(max_length=50,unique=True)
    time_created = DateTimeField(default=timezone.now)
    mostrecentscan=ForeignKey(Scan,on_delete=models.CASCADE,related_name='+',null=True)
    mostrecentscantime=DateTimeField()

消除mostrecentscantime 的问题出现在此查询中,我试图确定time_createdmostrecentscantime 大于7 天的所有条形码对象。

工作查询:

barcodematches = Barcode.objects.annotate(
    diff=ExpressionWrapper(F('mostrecentscantime') - F('time_created'), output_field=DurationField())
    ).filter(diff__gte=timedelta(days=7))

在这种情况下,我不能简单地引用mostrecentscan.time。我还尝试向 Barcode 添加一个 @property 字段,但也不起作用。

【问题讨论】:

  • F('mostrecentscan__time')?

标签: python django django-models django-queryset


【解决方案1】:

F 表达式在这种情况下可以遵循关系,所以这应该可以工作:

F('mostrecentscan__time') - F('time_created')

【讨论】:

  • 正是我需要的,现在我明白了如何在这种情况下使用 F 表达式。非常感谢!
猜你喜欢
  • 2022-10-05
  • 2020-08-15
  • 2021-11-28
  • 1970-01-01
  • 2015-11-02
  • 2020-01-19
  • 1970-01-01
  • 2018-02-25
  • 2011-10-12
相关资源
最近更新 更多