Get sublcass queryset only
KekeliDev opened this issue · 2 comments
I can't get queryset for a particular subclass only. I want to get only products relating that subclass only
- Django Model Utils version: 4.3.1
- Django version: 4.1
- Python version: 3.9
class Product(models.Model)
...
objects = InheritanceManager()
class Phone(Product)
...
class Laptop(Product)
...
How do I get querysets for the subclass Phone
without any other subclasses instances
I have gone through the documentation and didn't find any
I have built a custom filter that can do but it means I don't need the package and my concern is scalability of the custom implementation. I want to know if the package can help so I don't have to reinvent the wheel.
It's been a long time since I used the InheritanceManager
, but I would think:
Product.objects.select_subclasses(Phone).filter(phone__isnull=False)
or something ought to do the trick. The select_subclasses
would leave you with a heterogenous queryset of Product
and Phone
instances, so you'd subsequently want to only have Phone
instances, which you'd get by filtering out rows which don't have a product → phone relation.
That said. If you're after a homogenous queryset, why not just do:
Phone.objects.filter(...)
and ignore the inheritance part entirely? It'll effectively be roughly the same query and without the additional complexity.
Thank you very much this should work.
The trick I created earlier wouldn't scale very well as I have to load all products objects then load all Phone objects and use phone objects ids to do conditional check with if statements and even check for product status too.
I will use your suggestion even though I have embed category field in the product which are basically the subclasses so that I can filter on categories and no need to worry about subclassing.
I will adopt your suggestions because I want the database to handle queries not python functions