Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django best way to check the model type of a queryset

Tags:

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 
like image 330
wobbily_col Avatar asked May 29 '13 10:05

wobbily_col


People also ask

What is the type of QuerySet in Django?

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.

Is Django QuerySet lazy?

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.

How does Django define QuerySet?

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.


1 Answers

Ok, I see, I use is instead of isinstance():

if queryset.model is Library :     # do something.  
like image 59
wobbily_col Avatar answered Sep 19 '22 08:09

wobbily_col