Search code examples
pythondjangomodel

Python - Creating two models with 1-1 relationship in a same model.py file (hierarchy problem) in Django


Hey I'm facing this problem when I want to create 1:1 relationship IDK if I'm missing something here or what am I doing wrong

here in one app.model.py I'm trying to create 2 models like below :

class Manager(models.Model):
    user_id  = models.ForeignKey('BeautySalon.Salon',on_delete=models.DO_NOTHING)  #FK
    businessL_id = models.BooleanField(default = False, blank = False)
    salon_id = models.ForeignKey(Salon,on_delete=models.DO_NOTHING) #FK

class Salon(models.Model): 
    # name, manager_id--Manager, city_id--City, address, tell, description, starting hour , closing hour, PTG, rank--Rank
   
    name =  models.CharField(max_length=200)
    manager = models.ForeignKey(Manager,on_delete=models.DO_NOTHING)  # FK
    city =  models.ForeignKey(City,on_delete=models.DO_NOTHING)  #FK
    address = models.TextField(null = False, max_length = 1000)
    tell = models.CharField(max_length=24)
    description = models.TextField(null= False, max_length = 1000)
    strHour = models.TimeField()
    clsHour = models.TimeField()
    PTG = models.BooleanField(default = False, blank = False)
    rank = models.ForeignKey(Rank,on_delete=models.DO_NOTHING)  #FK
    

but when I try to make migrations I get this error Field defines a relation with model 'Salon', which is either not installed, or is abstract.

In C++ I would face the same problem but we could call the name at the top to let it know, IDK how to do it in python I've tried this : class Salon (models.Model): pass at the top of models.py file, but it didn't work .

I appreciate your help


Solution

  • I gues the problem is that you're referencing the Salon model before it's defined.

    Try move Salon class before Manager class in your code, or just wright it as a string in models.ForeignKey

    class Manager(models.Model):
        ...
        salon_id = models.ForeignKey('Salon', on_delete=models.DO_NOTHING)
        ...
    
    
    class Salon(models.Model)
        ...
        manager = models.ForeignKey('Manager', on_delete=models.DO_NOTHING)
        ...