Django, query filtering from model method

安稳与你 提交于 2019-11-28 18:05:45

You cannot query against model methods or properties. Either use the criteria within it in the query, or filter in Python using a list comprehension or genex.

You could also use a custom manager. Then you could run something like this:

Bar.objects.foo_active()

And all you have to do is:

class BarManager(models.Manager):
    def foo_active(self):
       # use your method to filter results
       return you_custom_queryset

Check out the docs.

I had similar problem: I am using class-based view object_list and I had to filter by model's method. (storing the information in database wasn't an option because the property was based on time and I would have to create a cronjob and/or... no way)

My answer is ineffective and I don't know how it's gonna scale on larger data; but, it works:

q = Model.objects.filter(...)...
# here is the trick
q_ids = [o.id for o in q if o.method()]
q = q.filter(id__in=q_ids)

You can't filter on methods, however if the is_active method on Foo checks an attribute on Foo, you can use the double-underscore syntax like Bar.objects.filter(foo__is_active_attribute=True)

class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
...

class Category(models.Model):
    ...
    open = models.BooleanField(default=True)

May be you can use simple filter, for this type of conditions.

Page.objects.filter(category__open=True)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!