Django model mapping problem

Asked

Viewed 44 times

2

The relationship between the classes in the Models.py file does not work because of the order of the classes (I think it has more to do with the interpreter) follows the problem:

class Producao(models.Model):
    empresa= models.OneToOneField(Empresa,null=False,blank=False,on_delete= models.PROTECT)

class Assinatura(models.Model):
    producoes= models.ManyToManyField(Producao,blank=False)

class Empresa(models.Model):
    assinatura=models.ManyToManyField(Assinatura, blank=True)

In the case of the variable empresa is giving error because for it the Company class does not exist, only that if I put the company class before the Production class the variable producoes It starts to get messy, and no matter how I organize it, it’s always gonna get messy because one depends on the other. How do I get the mapping fucionar?

1 answer

4


The "Enterprise" class does not yet exist when the class body "Production" is processed - it is no "problem", it is simply logical.

Django circumvents this by enabling Foreignkey classes to be passed as strings instead of the class object itself - so he creates the relationships in Azy fashion, and can find the true "Company" class when he actually creates the column in the bank.

In other words, write:

class Producao(models.Model):
    empresa= models.OneToOneField("Empresa",null=False,blank=False,on_delete= models.PROTECT)

in your code and it will work. (The other classes are declared in an order that it can use, so this is optional)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.