dl8
dl8

Reputation: 1270

Importing legacy database into django

So when you import a legacy database with the inspectdb function of django it states that you need to manually clean up "Rearrange models' order". In the documentation on the django website it states "In particular, you’ll need to rearrange models’ order, so that models that refer to other models are ordered properly.".

What exactly does this mean? If model A refers to model B, then model B should appear before model A within the file?

Upvotes: 1

Views: 273

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

In the documentation on the django website it states "In particular, you’ll need to rearrange models’ order, so that models that refer to other models are ordered properly."

What exactly does this mean?

In Python in general, in order to refer to any name, it needs to be defined first; because only then is it mapped; so this will result in an error:

print(hello)
hello = 'world'

Similarly, in models.py, when you are referring to another model class in any relationship; you have to make sure the class is declared before it is referred to - or you need to quote the class name. Since the inspection cannot guaratee the order of models being created, you get the warning. It is designed to prevent this scenario, which will result in an error:

class A(models.Model):
   foo = models.ForeignKey(B)

class B(models.Model):
   name = models.CharField(max_length=200)

To fix it, you can declare B before A:

class B(models.Model):
    name = models.CharField(max_length=200)

class A(models.Model):
    foo = models.ForeignKey(B)

Or use a string instead of the name:

class A(models.Model):
   foo = models.ForeignKey('B')

class B(models.Model):
   name = models.CharField(max_length=200)

Upvotes: 3

Related Questions