Django allows you to define the model you are referencing in the ForeignKey or ManyToManyField as '<app_name>.<model_name>' instead of importing the model and directly assigning it. This solves a lot of problems, especially circular imports.
Assuming you have categories applications with the Category model and products with the Product model, this is:
products/models.py :
class Product: categories = models.ManyToManyField(Category) name = models.CharField(max_length=255)
categories/models.py :
class Category: categories = models.ManyToManyField(self) name = models.CharField(max_length=255)
can directly translate to what you need:
products/models.py :
class Product: categories = models.ManyToManyField('categories.Category') name = models.CharField(max_length=255)
categories/models.py :
class Category: categories = models.ManyToManyField('self') name = models.CharField(max_length=255)
However, you can have as many categories as you want:
category_one = Category.create(name='Category one') category_two = Category.create(name='Category two') category_three = Category.create(name='Category three') category_three.categories.add(category_one, category_two) some_product = Product.create(name='Test Product') some_product.categories.add(category_three)
( ManyToManyField Docs )
It is also important to note that with any Python class, self not the class itself - it is an instance. Therefore, you cannot reference it outside the instance method, there is a good explanation of the reasons here . The only reason the 'self' line works is because Django translates this to the class it is in, categories.Category - so it would be nice to replace self with 'categories.Category' to be explicit.
source share