Django filter query with fields are automatically calculated

There is a Django order model with property fields that are automatically calibrated. How to execute a filter request.

class Order(models.Model):

    @property
    def expire(self):
        return self.created + datetime.timedelta(days=self.days_left())

    @property
    def days_left(self):
        return self.recurrence_period  * self._recurrence_unit_days[self.recurrence_unit]

The calculation is made to get 1,3,7 days from today

settings.SUBSCRIPTION_EXPIRATION_REMIND = [1, 3, 7]

days = map(lambda x: datetime.date.today() + datetime.timedelta(days=x), settings.SUBSCRIPTION_EXPIRATION_REMIND)

[datetime.date(2015, 7, 28),
 datetime.date(2015, 7, 30),
 datetime.date(2015, 8, 3)]

How to filter by ORM

Order.objects.filter(expire__in=days)

Django error.

FieldError: Cannot resolve keyword 'expire' into field.
+4
source share
3 answers

Finished adding expiration to the model, calculating the value of the save method. Now i can do

 Order.objects.filter(expire__in=days)
-2
source

No, you cannot search by model methods or properties. Django ORM does not allow this.

SQL , Python, . , Django .

:

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

:

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

, .

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

Order, expire days.

+15

, , 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

+1

All Articles