Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

python - Django filter query on with property fields automatically calculated

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

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]

Calculation done to get 1,3,7 datetime 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 query

Order.objects.filter(expire__in=days)

Django is throwing error.

FieldError: Cannot resolve keyword 'expire' into field.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...