Custom properties in a query

我只是一个虾纸丫 提交于 2019-12-06 10:14:44

Instead of calculating the status as a property, create a proper model field for it and update it in the save method. Then you can use that field directly in the query.

You cannot use a custom property in query, since Django's ORM will try to map it to a database column and fail. Of course you can use it in an evaluated queryset, e.g. when you're iterating about the objects of a query's results!
You can only filter for things like: Event.objects.filter(date_drafted__isnull=False). http://docs.djangoproject.com/en/dev/ref/models/querysets/#isnull

Thanks to Daniel. I think that I might use your approach. However, I also managed to get it working using the queryset 'extra' method, which might also be useful to other people, although its probably isn't database agnostic.

qs = Event.objects.extra(select={'current_status_id': 
            '''(CASE 
            WHEN date_cancelled THEN 0
            WHEN date_closed THEN 6
            WHEN date_signed_off THEN 5
            WHEN date_reported THEN 4
            WHEN date_accepted THEN 3
            WHEN date_registered THEN 2
            WHEN date_drafted THEN 1
            ELSE 99
            END)
            '''})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!