以下面的伪代码为例
models.py
from django.db import models
from django.core.exceptions import ValidationError
from .methods import list_eligible_badges
class User(models.Model):
handle = models.SlugField(max_length=200)
class Permission(models.Model):
user = models.ForeignKey(User)
badge = models.SlugField(max_length=200)
def clean(self):
super(Permission, self).clean()
allowed_badges = list_eligible_badges()
try:
allowed_badges.index(self.badge)
except:
raise ValidationError('This user is not eligible for this privilege')
methods.py
from .models import User
def list_eligible_badges(user_handle):
user_in_context = User.objects.get(handle=user_handle)
# do some validation on the user_in_context to figure out what
# badge is this user eligible for then return a list of badges
# allowed for this user
上面的代码定义了两个相关的数据模型,User
并且Permission
其中每个许可与用户相关联。在文件中,methods.py
我们有一个方法,list_eligible_badges
其中该方法采用user_handle(用户的唯一段标识符),并返回该特定用户有资格获得的权限的段列表。
然后list_eligible_badges
,在Permission
模型的clean函数中使用该方法,以在将每个权限添加到数据库之前验证每个权限。
一切似乎都很好,除了运行代码时,它显示错误:
在第1行的文件“ methods.py”中
来自.models import用户
ImportError:无法从“ .models”导入名称“ User”
即使methods.py
从除其他模块以外的其他模块导入时未显示此错误models.py
看起来这会创建某种导入循环!作为两个文件,models.py
并且methods.py
彼此导入。不幸的是,我必须在list_eligible_badges
外部定义该方法,因为它将被其他多个模块重用,并且如果不导入User
数据模型就无法定义它。
那我该如何处理呢?有没有像PHP的require_once这样的东西在python中?
您可以做的一件事是在本地导入:
class Permission(models.Model):
user = models.ForeignKey(User)
badge = models.SlugField(max_length=200)
def clean(self):
from .methods import list_eligible_badges
super(Permission, self).clean()
allowed_badges = list_eligible_badges()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句