3

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?

1

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir. Now i can load my model from a str
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.