Django filter query on with property fields automatically calculated

前端 未结 3 692
深忆病人
深忆病人 2020-12-17 14:04

There is Django Order model with property fields automatically calucated. How to do a filter query.

class Order(models.Model):

    @property
    def expire(         


        
相关标签:
3条回答
  • 2020-12-17 14:51

    Ended up adding expire to model, calculating the value on save method. Now i can do

     Order.objects.filter(expire__in=days)
    
    0 讨论(0)
  • 2020-12-17 14:58

    No, you can't perform lookup based on model methods or properties. Django ORM does not allow that.

    Queries are compiled to SQL to be sent and processed at the database level whereas properties are Python code and the database knows nothing about them. That's the reason why the Django filter only allows us to use database fields.

    Can do this:

    Order.objects.filter(created=..) # valid as 'created' is a model field
    

    Cannot do this:

    Order.objects.filter(expires=..) # INVALID as 'expires' is a model property
    

    You can instead use list comprehensions to get the desired result.

    [obj for obj in Order.objects.all() if obj.expire in days]
    

    The above will give me the list of Order objects having expire value in the days list.

    0 讨论(0)
  • 2020-12-17 14:58

    I dont think you can use a property in the field lookups as the doc says The field specified in a lookup has to be the name of a model field https://docs.djangoproject.com/en/1.8/topics/db/queries/#field-lookups

    0 讨论(0)
提交回复
热议问题