【问题标题】:Django: How to filter model property in viewsDjango:如何在视图中过滤模型属性
【发布时间】: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


    【解决方案1】:

    你应该使用注释:

    models.TransactionData.objects.annotate(product_name=YOUR_ANNOTATION)
    

    之后,您可以将product_name 作为字段访问并按该字段进行过滤

    文档在:https://docs.djangoproject.com/en/3.2/ref/models/querysets/#annotate

    【讨论】:

    • 我按照你的建议使用了注释,但由于 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)
    • 我怀疑您的产品名称查询有点复杂,难以作为注释轻松编写。虽然不是理想的数据库设计,但您可以在模型中添加 product_name 字段,然后使用属性方法中的代码并覆盖 model.save() 以在每次模型更改时设置新字段。
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2019-08-23
    • 2020-12-21
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多