I have a Django action function which I would like to use on querysets based on different models.
What is the best way to check the model type my queryset is composed of? Say I want to check for a Library class that is defined in my models.py
At the moment I can get it to work using
for object in queryset : if object.__class__.__name__ == "Library"
But I am sure there is a better way of doing this.
I assume somehow I do something using queryset.model. I have tried the following, but it doesn't do what I want it to:
import myapp.models.Library def my function(modeladmin,request queryset ) if isinstance(queryset.model , Library ) : # do something specific here
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.
A queryset is simply a list of objects from the Django Models. When using the Django ORM creating a new row in the table is simply like creating a new object of Model class. Django ORM maps these Model objects to Relational database query. Any SQL query can be written easily as Django queryset.
Ok, I see, I use is instead of isinstance():
if queryset.model is Library : # do something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With