从models.py导入类的Django技巧

3

使用这样的文件夹结构:

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

在我的views.py中如何导入在models.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个回答

15

使用:

from library.models import MyClass

然后你应该就可以开始了 :)

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

更新:

问题几乎肯定是你的模型以 '7' 开头 - 将其更改为字母字符,一切都会好起来的,我几乎确定 :)


我没有一个真正的项目应用程序结构。只有一个项目。 - hanleyhansen
你有一个名为“library”的项目,在其中有一个名为“library”的应用程序... - simon
好的,我明白你的意思。所以这应该可以工作:从library.models导入7DTagmap,但它没有,所以我一定漏掉了什么。 - hanleyhansen
1
在Python中,任何标识符(变量或类名)只能以字母或下划线 _ 开头。 - Burhan Khalid
3
不仅仅是PEP8规范,它也存在于Python语言的词法分析器中。链接为:http://docs.python.org/2/reference/lexical_analysis.html#identifiers - Burhan Khalid
显示剩余3条评论

3
例如在你的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

尝试了这个:从library.models导入7DTagmap,但是没有起作用。 - hanleyhansen
我使用了Django的inspectdb功能,它将其生成为类名。 - hanleyhansen
问题中添加了错误。 - hanleyhansen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接