我正在尝试消除 Barcode 模型中冗余的字段。不需要 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
和 time
的 mostrecentscan
大于 7 的所有 Barcode 对象天。
工作查询:
barcodematches = Barcode.objects.annotate(
diff=ExpressionWrapper(F('mostrecentscantime') - F('time_created'), output_field=DurationField())
).filter(diff__gte=timedelta(days=7))
在这种情况下,我不能简单地引用 mostrecentscan.time
。我还尝试向 Barcode 添加一个 @property 字段,但它也不起作用。