user3541631
user3541631

Reputation: 4008

Using a Raw Queryset inside a Custom Model Queryset

I want to use a raw queryset inside a custom model queryset.

The issues is that I need to use/declare the queryset based model, before the model class is declared.

Can I declare a substitute of the model, that will be interpreted at the execution time ?

So, the code is like this:

class EntityModelQuerySet(models.query.QuerySet):

    def search_by_item(self, id__list):

            qs = Entity.objects.raw(


.............

class Entity

What about a second model with prefetch_related

qs = Entity.objects.raw( .. queryset = .prefetch_related(
            Prefetch('item',
                     queryset=EntityItem.objects.all().only(name)

Upvotes: 0

Views: 203

Answers (1)

Alexandr Tatarinov
Alexandr Tatarinov

Reputation: 4034

Just use self.raw(...) instead of Entity.objects.raw()

class EntityModelQuerySet(models.QuerySet): # use models.QuerySet
    def search_by_item(self, id__list):
        qs = self.raw(...)
        return qs

class Entity(models.Model):
     objects = EntityModelQuerySet.as_manager()

Upvotes: 1

Related Questions