2

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?

minakraka
  • 53
  • 2
  • 5
  • Possible duplicate of [Django: Get model from string?](https://stackoverflow.com/questions/4881607/django-get-model-from-string) – Antwane Oct 26 '18 at 14:18

2 Answers2

12

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)
Antwane
  • 20,760
  • 7
  • 51
  • 84
3

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89