I have two models: Product
and User
class Product(models.Model):
#here are information fields about Product
likes = models.ManyToManyField(
User, related_name="product_likes", blank=True)
object = models.Manager()
productobjects = ProductObjects()
def __str__(self):
return self.name
class User(AbstractBaseUser, PermissionsMixin):
#here are information fields about User
followed = models.ManyToManyField(
Product, related_name="followed_products", blank=True)
objects = CustomAccountManager()
object = models.Manager()
def __str__(self):
return self.email
Inside Product
I need to have a likes
filed ManyToMany which store which users liked the product. Inside User
I need to have followed
field ManyToMany which store which products the user follow.
I have an error: cannot import name 'Product' from partially initialized module 'product.models' (most likely due to a circular import)
. How can I fix it? Or maybe can I do this differently?
I think the problem is that inside product.models
I import: from users.models import User
and inside users.models
I import: from product.models import Product
.
(I am using the likes
filed just to GET number of likes, but from followed
I need to GET all the products that specified user follow and informations about them)
CodePudding user response:
Your Product
model needs to import the User
model and vice versa. As a result the imports got stuck in an infinite loop.
You can however use a string literal to specify to what model your ManyToManyField
is pointing. For example:
# no import of the models module where you define User
class Product(models.Model):
#here are information fields about Product
likes = models.ManyToManyField(
'app_name.User', related_name="product_likes", blank=True
)
# ⋮
Here app_name
is the name of the app where you defined the (custom) user model.
Since it is (likely) the user model, you here can use the AUTH_USER_MODEL
setting [Django-doc]:
# no import of the models module where you define User
from django.conf import settings
class Product(models.Model):
#here are information fields about Product
likes = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="product_likes", blank=True
)
# ⋮