[Fixed]-How to solve the circular import error in django?

39๐Ÿ‘

โœ…

Use to='<app_lable>.<Model Name>' in Foreignkey and ManytoMany Fields

Remove import models from file add foreignkey and manytomany fields in model like i did in below code.to='consult.Question'
When we create migrations from makemifration command that use hardcode model name in migration file, So use same way to write Foreignkey and Manytomany field

from django.contrib.auth.models import User 
from django.db import models
class Customer(models.Model): 
    name = models.ForeignKey(User, null=True) 
    gender = models.CharField(max_length=100)
    skin_type = models.CharField(max_length=1000)
    hair_type = models.CharField(max_length=1000)
    bookmarked = models.ManyToManyField(to='consult.Question')

    def __str__(self):
        return str(self.name)
๐Ÿ‘คNeeraj Kumar

5๐Ÿ‘

Try changing your imports into this:
in consult/models.py

import main.models.Customer

in main/models.py

import consult.models.Question
import consult.models.Reply

Then instead of Customer you use main.models.Customer and instead of Question or Reply you use import consult.models.Question and consult.models.Reply

๐Ÿ‘คomu_negru

3๐Ÿ‘

Another way to resolve circular imports is to do:

from django.apps import apps
MyModel = apps.get_model('myapp', 'MyModel')
๐Ÿ‘คCraig Wallace

1๐Ÿ‘

You can do this remove from main.models import Customer
and in the class

class Question(models.Model):
    name = models.ForeignKey("main.Customer",related_name="customerQuestion", on_delete=models.CASCADE)

class Reply(models.Model):
    user = models.ForeignKey("main.Customer",related_name="customerReply", on_delete=models.CASCADE)
๐Ÿ‘คasupriatna

Leave a comment