Home > Back-end >  cannot import name 'Categories' from partially inisialized module 'categories.models&
cannot import name 'Categories' from partially inisialized module 'categories.models&

Time:01-28

I try to create 2 database categories and sous_categories in Django. in these 2 database a categories can have many sous_categories and sous_categories has only one categories. When i test my code i got the 'cannot import name 'Categories' from partially initialized module 'categories.models' (most likely due to a circular import)'.

I think the error occurs to a circular dependency and the most solution i see int the web is: it can be resolved by moving the imported classes to a third file and importing them from this file. But i don't know how to do it with my code.

here part of my categories model:


class Categories(models.Model):
    
    nom_categorie = models.CharField(max_length=200)
    marchand = models.ManyToManyField(Marchands)
    sous_categorie = models.ManyToManyField(Sous_Categories)
    slug = models.SlugField(default='')
    images = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(null=True)```
`
    and my sous_categories model:

``from django.db import models
from django.template.defaultfilters import slugify
from categories.models import Categories

class Sous_Categories(models.Model):
    nom_souscategorie = models.CharField(max_length=200)
    categorie = models.ForeignKey(Categories, on_delete=models.SET_NULL, null=True, blank=True)
    slug = models.SlugField(default='')
    images = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(null=True)``

CodePudding user response:

Try to pass in a string Categories model instead of directly pass like this

class Categories(models.Model):
    
    nom_categorie = models.CharField(max_length=200)
    marchand = models.ManyToManyField(Marchands)
    sous_categorie = models.ManyToManyField(Sous_Categories)
    slug = models.SlugField(default='')
    images = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(null=True)```


class Sous_Categories(models.Model):
    nom_souscategorie = models.CharField(max_length=200)
    categorie = models.ForeignKey('app_name.Categories', on_delete=models.SET_NULL, null=True, blank=True)
    
  • Related