jazzband / django-polymorphic

Improved Django model inheritance with automatic downcasting
https://django-polymorphic.readthedocs.io
Other
1.65k stars 280 forks source link

Automatic instance_of() on Model.objects ? #72

Open NotSqrt opened 10 years ago

NotSqrt commented 10 years ago

Hi !

When you have models like:

class ModelA(PolymorphicModel):
    pass

class ModelB(ModelA):
    pass

class ModelC(ModelA):
    pass

It would be nice to be able to do:

>>> ModelB.objects.all()
[<only ModelB instances, not ModelC>]

without the addition of instance_of everytime.

I have a simple solution, and am looking for comments/other ways to do this:

class InstanceOfPolymorphicManager(PolymorphicManager):
    def get_query_set(self):
        queryset = super(InstancePolymorphicManager, self).get_query_set()
        return queryset.instance_of(self.model)

class ModelA(PolymorphicModel):
    objects = InstanceOfPolymorphicManager()
    # no need to repeat it in subclasses, the manager will pick the proper model to use in "instance_of(self.model)
vdboor commented 10 years ago

Hi,

I'm a bit surprised to see this issue. Projects that I run on polymorphic completely depend on the fact that ModelB won't return instances of other types. That's in fact standard behavior.

Do you have a test case to prove that is not the case? Could there be an overwritten Manager sitting in your models somewhere?

NotSqrt commented 10 years ago

yeah, you're probably right, I will check my intermediate managers..

cesarcruz commented 7 years ago

I have similar problem (in my case I only get ModelA), but your solution of creating manager InstanceOfPolymorphicManager does not works for me, so I finally find this way, it is not a queryset but a list but it solved my problem: ModelA.objects.get_real_instances()