![](/img/trans.png)
[英]How to create a filter on the ForeignKey Field in a Django Model?
[英]Django filter based on ForeignKey model field
我試圖消除冗余的條形碼模型字段。 mostrecentscantime
條碼的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天。
工作查詢:
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
表達式可以遵循關系,所以這應該有效:
F('mostrecentscan__time') - F('time_created')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.