0

I'm trying to get all loyal clients in my Django app. For this, I'm trying to filter a queryset using a method, rather than an attribute, and I don't know how to do this. EDIT : using Kedar advice, I tried to to this with @property decorator

class Client(models.Model):

    @property
    def is_loyal(self):
        # ...
        # Return True or False

    @classmethod
    def get_loyal_clients_since(cls):

        # Method #1: works but clearly a workaround
        base_clients = cls.some_method_to_retrieve_special_clients()
        clients_list = [c.pk for c in base_clients if c.is_loyal()]
        clients = cls.objects.filter(pk__in=clients_list)

        # Method #2: does not work
        clients = cls.some_method_to_retrieve_special_clients() \
                  .filter(is_loyal=True)

Error: Cannot resolve keyword 'is_loyal' into field.

David Dahan
  • 10,576
  • 11
  • 64
  • 137
  • you can make `is_loyal` a property (https://docs.djangoproject.com/en/1.7/glossary/#term-property). Then the filtering should work. – Kedar Mar 23 '15 at 13:36
  • Very good idea, but it does not seem to work (`Cannot resolve keyword 'is_loyal' into field.`) – David Dahan Mar 23 '15 at 13:44
  • Wouldn't a Manager for the "loyal" clients just do that ? I'm not that sure what you are looking for, but as Managers return querysets, you would be able to filter afterwards. See https://docs.djangoproject.com/en/1.7/topics/db/managers/ – giant_teapot Mar 23 '15 at 13:49
  • If I use a manager to filter loyal clients THEN calling my `some_method()` it will be definitely slower. I really need to call `some_method()` first, then get the loyal ones then. :( – David Dahan Mar 23 '15 at 13:56
  • @kedar? You sure it works that way? Just found out on this thread it seems to be impossible: http://stackoverflow.com/questions/1205375/filter-by-property – David Dahan Mar 23 '15 at 14:14
  • My mistake, I am checking the property when iterating, can't filter. You are correct. – Kedar Mar 23 '15 at 14:21
  • if you need to filter on this you need to be able to do it in an SQL query... you need to be able to express the logic of `is_loyal` property in terms of fields in the db... if you can do that it may be possible in Django ORM – Anentropic Mar 23 '15 at 17:10

0 Answers0