minakraka
minakraka

Reputation: 63

How to convert string to call model's name in Django?

view.py

from .models import Banana, Mango
list = request.GET['fruit[]']
for x in list:
    conn = x.objects.all()
    print(conn.name)

in html file: I use checkbox to choose "Mango" and "Banana", and view.py get the value of checkbox. Then I want to select the model of user choices.

when I run this code, it is appear AttributeError at /search 'str' object has no attribute 'objects'.

In that's code, I want to return name value of objects model in my models.py

How I can replace string in List to call object models in django?

Upvotes: 3

Views: 5018

Answers (2)

Antwane
Antwane

Reputation: 22598

If you have to load your model from a str value, use django.apps.get_model() helper

from django.apps import apps

Model = apps.get_model('app_name', 'model_name')
for element in Model.objects.all():
    print(element)

Upvotes: 12

user2390182
user2390182

Reputation: 73460

Put the model classes themselves in the list ...

from .models import Banana, Mango

lst = [Banana, Mango]  # do not call variable 'list'
# ...

... and you won't have to do any string-to-model conversion at all.

Upvotes: 3

Related Questions