【发布时间】: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_created 和mostrecentscan 的time 大于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