3

I would appreciate your help with following problem. Lets use models from Django documentation to illustrate my situation.

models.py

from django.db import models

class Place(models.Model):
    owner = DjangoModels.ForeignKey('Owner', related_name='places')
    objects = PassThroughManager.for_queryset_class(PlaceQuerySet)()

class Restaurant(Place):
    ... some members ...
    objects = PassThroughManager.for_queryset_class(RestaurantQuerySet)()

class Pub(Place):
    ... some members ...
    objects = PassThroughManager.for_queryset_class(PubQuerySet)()

class Owner(models.Model):
    ... some members ...

queryset.py

class PlaceQuerySet(DjangoModels.query.QuerySet):
    .. common place filters ...

class RestaurantQuerySet(PlaceQuerySet):
    .. restaurant specific filters ...

class PubQuerySet(PlaceQuerySet):
    .. pub specific filters ...

So as you can see above I have one base model 'Place' and two sub models 'Restaurant' and 'Pub'. Base model 'Place' has a link to 'Owner' object. Querysets (PlaceQuerySet, RestaurantQuerySet, PubQuerySet) have the same inheritance hierarchy like models (Place, Restaurant, Pub).

The challenge I am having is to somehow retrieve PubQuerySet containing only Pub objects linked to certain owner....


I know that one way to do what I need is to add owned_by(owner) filter into PubQuerySet and call following:

Pub.objects.owned_by(owner)

but it has performance issues because '.objects' does not use prefetched results and it always hits DB.


My thoughts:

When I call

# owner is instance of Owner class
>>owner.places.all()

it returns

PlaceQuerySet[<Place object ><Place object ><Place object >....]

But how do I get

PubQuerySet[<Pub object ><Pub object >]

???

I know that with select_subclasses() method from django-model-utils(1) I can downcast objects in Queryset so if I do something like this

# owner is instance of Owner class
>>owner.places.select_subclasses('pub')

I would get PlaceQuerySet with instances of Pub class

PlaceQuerySet[<Pub object ><Pub object >]

but still I will receive PlaceQuerySet and not PubQuerySet...

Thank you very much for your help

Jano

  • 1
    I can't imagine why the queryset class would matter, can you explain? You'd just iterate through the queryset anyway right? – tuxcanfly Oct 07 '13 at 05:58
  • 1
    Hi.The class of query set matters, because I need to chain more filters on that queryset and those filters are available only in PubQuerySet. The other reason is that if you are working with PlaceQUerySet then you can filter based on members of Place class only.In my case I would like to filter based on members of Pub class. Thank you for your help.. – user2852277 Oct 07 '13 at 07:05
  • ah, makes sense, might there be a way to cast it into the other queryset or instantiate the new queryset and set some attributes... – tuxcanfly Oct 07 '13 at 07:11

0 Answers0