[英]Import current module from an imported module in python Django (importing loops)
以下面的伪代码为例
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(用户的唯一 slug 标识符)并返回该特定用户有资格获得的权限的 slug 列表。
然后在Permission
model 的干净 function 中使用list_eligible_badges
方法来验证每个权限,然后再将其添加到数据库中。
一切似乎都很好,除了运行代码时,它显示错误:
文件“methods.py”,第 1 行,在
from.models 导入用户
ImportError:无法从“.models”导入名称“用户”
即使从models.py
以外的任何其他模块导入methods.py
时它没有显示此错误
看起来这会创建某种导入循环,因为models.py
和methods.py
这两个文件都是相互导入的。 不幸的是,我必须在外部定义方法list_eligible_badges
,因为它将被多个其他模块重用,如果不导入User
数据 model,我就无法定义它。
那么我该如何处理呢? python 中是否有类似 PHP 的 require_once 的东西?
您可以做的一件事是在本地导入:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.