【发布时间】:2023-03-31 18:18:02
【问题描述】:
请问如何使用模型@property 方法过滤视图中的查询集。
class TransactionData(models.Model):
Nozzle_address = models.CharField(max_length=255)
Device = models.ForeignKey(Devices, on_delete=models.CASCADE)
Site = models.ForeignKey(Sites, on_delete=models.CASCADE, enter code hererelated_name='transaction_data')
Pump_mac_address = models.CharField(max_length=255)
@property
def product_name(self):
try:
return f'{(Nozzle.objects.filter(Pump__Device__Device_unique_address=self.Pump_mac_address,Nozzle_address=self.Nozzle_address)).Product.Name}'
except :
pass
基本上我希望能够在这样的视图中编写查询:
filtered_product = models.TransactionData.objects.filter(Site=Site_id, product_name='kero')
但是 django 不支持这个。我想我需要编写一个自定义管理器,然后我可以像这样查询
filtered_product = models.TransactionData.objects.filter(Site=Site_id).product_name('Key')
问题是在属性方法 product_name 中使用了另一个模型,例如 Nozzle
请问我怎样才能完成这项工作...我知道我需要使用自定义管理器或查询集来完成这项工作,但无法弄清楚.. 非常感谢您的帮助。谢谢
@Amin 我按照您的建议使用了注释,但由于 self 引用了模型实例,因此未定义,因此无法正常工作......感谢任何帮助。 即
models.TransactionData.objects.annotate(product_name=(models.Nozzle.objects.filter(Pump__Device__Device_unique_address=self.Pump_mac_address,Nozzle_address=self.Nozzle_address)).Product.Name)
【问题讨论】:
标签: django filter model django-queryset django-custom-manager