Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get_models with models/__init.py__

Tags:

python

django

I'm having a problem using get_model and get_models in django

I have several models under models/

 models/blog.py
 models/tags.py
 models/users.py
 models/comments.py
 models/category.py

And a models/__init.py__

from myapp.models.blog import *
from myapp.models.tags import *
from myapp.models.users import *
from myapp.models.comments import *   
from myapp.models.category import *

However in my views.py I have some code to use get_model

from django.db.models.loading import get_model
blog_class = get_model('myapp', 'blog') #Returns none

When I try get_models('myapp') it returns an empty list.

I also tried

print(get_app('myapp'))

Which returns:

<module 'myapp.models' from '/var/www/myapp/models/__init__.pyc'> 

And if I try to iterate over it

for model in get_models(get_app('myapp')):
    print(model)

It does nothing. Is there anything I'm missing or failing to spot?

like image 981
Shane Avatar asked Jul 31 '12 11:07

Shane


1 Answers

Because you haven't defined your models in the app's models.py, you must explicitly set the app_label option for each model.

class Blog(models.Model):
    title = models.CharField(max_length=30)
    ...

    class Meta:
        app_label = 'myapp'
like image 99
Alasdair Avatar answered Oct 14 '22 06:10

Alasdair