Django Import Class来自models.py

时间:2013-08-28 03:52:41

标签: python django django-models django-views

使用这样的文件夹结构:

library/
-django.wsgi
-manage.py
-static/
    --all my static files
-library/
    --__init__.py
    --models.py
    --settings.py
    --urls.py
    --views.py
    --wsgi.py
    --templates/
        ---where i plan to store all my templates

如何在models.py?

中定义的views.py中导入类

我试过了:

from . import models.class

from models import class

from projectname.models import class

from projectname import models.class

from project import class

但对于所有那些我得到无效的语法错误

views.py

from django.core.context_processors import csrf
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.contrib import messages
from django.template import RequestContext, loader
from django.contrib.auth import logout

from library.models import 7DTagmap

models.py

from __future__ import unicode_literals

from django.db import models

class 7DTagmap(models.Model):
   id = models.IntegerField(primary_key=True)
    tag_id = models.CharField(max_length=50L)
    st_tag_id = models.IntegerField()
    class Meta:
        db_table = '7d_tagmap'

错误:

invalid syntax (views.py, line 11)
Exception Type: SyntaxError
Exception Value:    invalid syntax (views.py, line 11)

2 个答案:

答案 0 :(得分:12)

使用:

from library.models import MyClass

你应该好好去:)

(基本结构为from <app>.models import <ModelName>

<强>更新

问题是(几乎!)当然,你的模型始于&#39; 7&#39; - 把它改成一个字母字符,一切都会很好,我(几乎!)确定:))

答案 1 :(得分:2)

例如,在你的models.py中:

from django.db import models
from django.contrib.auth.models import User

class register(models.Model):  
    user = models.OneToOneField(User)

然后在views.py中,您可以这样打电话:

from library.models import register