EazyC
EazyC

Reputation: 819

Django Template: How to determine which object/model a queryset is composed of?

I’ve written a search function for my django app which does a number of different filtering depending on the search string entered in the search box. I save the result of these different query filtering in a variable called ‘results’ (seems appropriate), but I am having trouble getting the template to render the variable properly depending on the type of object the queryset is based on. The results variable can either take the form of a queryset of ‘filtered’ object1 or 0 results (if nothing of object1 matched that search) OR it can take the form of a queryset of 'filtered' object2 or 0 results (if nothing of object2 matched that search). Later this might become many more different objects/models understandably so I would like to know how to check what type of object the queryset is composed of.

Any help would be really appreciated.

Upvotes: 1

Views: 2113

Answers (2)

Seb D.
Seb D.

Reputation: 5205

Given a Django queryset, you can retrieve its model using the well named model attribute, that gives a Model object.

queryset = SomeModel.objects
print queryset.model  # prints 'path.to.your.app.models.SomeModel'

You probably do not want to check against the full path, so you can use __name__

print queryset.model.__name__  # prints 'SomeModel'

But since you cannot access underscore attributes in templates, you'll have to add this information in your view.

Update: To check what is the model name in the template, you can add it on the queryset object:

queryset.model_name = queryset.model.__name__   

Then in your template:

{% if queryset.model_name = 'SomeModel' %}
    ... do something
{% elif queryset.model_name = 'SomeOtherModel' %}   
    ....
{% endif %}

Upvotes: 5

Evgeny Ivanov
Evgeny Ivanov

Reputation: 40

1) Checking for a zero 2) checking for the field ".name" of the first element of selection. also get class name for empty queryset in django - class - name - for - empty - queryset - in - django

If did not turn out, please code

Upvotes: 1

Related Questions