如何在另一个模型(Django)中使用过滤器方法作为用户模型
我有一个自定义的用户模型:
# accounts > models.py > ...
class MyUser(AbstractUser):
[...]
fallowing_tags = models.ManyToManyField('posts.tag', blank=True)
我想过滤所有跌入特定标签的用户:
from accounts.models import MyUser as User
# ---- or -----
from django.contrib.auth import get_user_model
User = get_user_model()
class Tag(models.Model):
name = models.SlugField(max_length=50, unique=True)
@property
def fallowers(self):
return User.objects.filter(fallowing_tags=self)
但是该程序给出了一个错误:
File "~/path/to/blog/accounts/models.py", line 13, in <module>
from posts.models import Tag, Post
File "~/path/to/blog/posts/models.py", line 3, in <module>
from accounts.models import MyUser as User
ImportError: cannot import name 'MyUser' from partially initialized module 'accounts.models' (most likely due to a circular import) (~/path/to/blog/accounts/models.py)
I have a custom user model:
# accounts > models.py > ...
class MyUser(AbstractUser):
[...]
fallowing_tags = models.ManyToManyField('posts.tag', blank=True)
And I want to filter all users who fallowed a specific tag:
from accounts.models import MyUser as User
# ---- or -----
from django.contrib.auth import get_user_model
User = get_user_model()
class Tag(models.Model):
name = models.SlugField(max_length=50, unique=True)
@property
def fallowers(self):
return User.objects.filter(fallowing_tags=self)
But the program gives an error:
File "~/path/to/blog/accounts/models.py", line 13, in <module>
from posts.models import Tag, Post
File "~/path/to/blog/posts/models.py", line 3, in <module>
from accounts.models import MyUser as User
ImportError: cannot import name 'MyUser' from partially initialized module 'accounts.models' (most likely due to a circular import) (~/path/to/blog/accounts/models.py)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django会自动添加相反的关系,因此 no 需要添加
关注者
,您可以查询:如果要更改名称,您可以设置<< a href =“ https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.foreignkey.related_name” rel =“ nofollow noreflow noreferrer”> … 参数&nbsp; [django-doc] ,例如:
然后,您因此对:
Django automatically adds a relation in reverse, so there is no need to add a
followers
, you can query with:If you want to change the name, you can set the
related_name=…
parameter [Django-doc], for example with:Then you thus query with:
它是
Importerror
,我认为这是因为此行从accounts.models导入myuser作为用户
。它可能与Django的内置用户
模型相抵触,该模型在django.contrib.auth
中。尝试将其更改为另一个名称。好吧,我认为您也可以简单地使用
myuser
。尝试:
或
注意:
请不要给任何有可能与Django库发生冲突的名称。It is
ImportError
and I think, it is because of this linefrom accounts.models import MyUser as User
. It may be conflicting with django's inbuiltUser
model which is indjango.contrib.auth
. Try changing it to another name.Well, i think you can also simply use
Myuser
.Try:
OR
Note:
Please don't give any name which has a possibility to conflict with django's libraries.