0

I'm using a CustomQuerySet using Custom QuerySet and Manager without breaking DRY?. I can only access custom functions using objects. Here's my Code:

class CustomQuerySetManager(models.Manager):
    """A re-usable Manager to access a custom QuerySet"""
    def __getattr__(self, attr, *args):
        print(attr)
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            # don't delegate internal methods to the queryset
            if attr.startswith('__') and attr.endswith('__'):
                raise
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
        return self.model.QuerySet(self.model, using=self._db)


class SampleModel(models.Model):
    objects = CustomQuerySetManager()

    class QuerySet(models.QuerySet):
        def test(self):
            print("test function was callsed")

With this these happens:

SampleModel.objects.test() # This works
SampleModel.objects.all().test() # This doesnt works...

Why does this happen?

Myzel394
  • 1,155
  • 3
  • 16
  • 40
  • 1
    Because the `.all()` returns a `QuerySet` (not the one you defined, but the "vanilla" `QuerySet`). Your own `QuerySet` after all implements these methods, and a `QuerySet` always makes a *copy*, so the output `.all()` is *not* the same `QuerySet` object, it is a new `QuerySet`, but with the same data. – Willem Van Onsem May 05 '19 at 15:59
  • Is there any way to not get the "vanilla" `Queryset`? This answer (https://stackoverflow.com/a/2163921/9878135) says it should be possible. Do you have any idea? – Myzel394 May 05 '19 at 16:05
  • @Myzei394: yes, you will need to patch all methods to wrap the result in your `CustomQuerySet`. See the source code of the `QuerySet`: https://github.com/django/django/blob/master/django/db/models/query.py#L185 – Willem Van Onsem May 05 '19 at 16:06
  • @WillemVanOnsem Idk what you mean with patch. I've never done this. Can you give me an example please? – Myzel394 May 05 '19 at 16:14

0 Answers0