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)
CodePudding user response:
Django automatically adds a relation in reverse, so there is no need to add a followers
, you can query with:
mytag.myuser_set.all()
If you want to change the name, you can set the related_name=…
parameter [Django-doc], for example with:
class MyUser(AbstractUser):
# …
fallowing_tags = models.ManyToManyField(
'posts.tag',
blank=True,
related_name='users'
)
Then you thus query with:
mytag.users.all()
CodePudding user response:
It is ImportError
and I think, it is because of this line from accounts.models import MyUser as User
. It may be conflicting with django's inbuilt User
model which is in django.contrib.auth
. Try changing it to another name.
Well, i think you can also simply use Myuser
.
Try:
from accounts.models import MyUser
OR
from accounts.models import MyUser as anyAnotherName
Note:
Please don't give any name which has a possibility to conflict with django's libraries.