Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get sublcass queryset only #549

Open
KekeliDev opened this issue Dec 14, 2022 · 2 comments
Open

Get sublcass queryset only #549

KekeliDev opened this issue Dec 14, 2022 · 2 comments

Comments

@KekeliDev
Copy link

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.

@kezabelle
Copy link
Collaborator

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.

@KekeliDev
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants