Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward class declaration in Python

I have two classes in order:

class A(models):
    ...

class B(models):
    a = models.ManyToManyField(A)

Now I have to change my model to one below:

class A(models):
    b = models.ManyToManyField(B)

class B(models):
    ...

I have to use south migrations. I wanted to create new many to many field in class A, migrate data and delete field from class B. The problem is that both are in same model. So when I put many to many into A class it cannot be seen. Because B declaration is below A. How to solve this problem?

like image 351
szaman Avatar asked Mar 15 '11 07:03

szaman


People also ask

Can you forward declare a class in Python?

There is no way to directly declare forward-references in Python, but there are several workarounds, a few of which are reasonable: 1) Add the subclasses manually after they are defined. 2) Create Base. 3) Create Base.

What is forward in Python class?

forward() is similar to call method but with registered hooks. This is used to directly call a method in the class when an instance name is called. These methods are inherited from nn. Module.

What is forward reference in Python?

Forward references are type annotations which use a string literal to declare a name that hasn't been defined yet in the code. The annotation is stored as just the name and the reference to the object is resolved later.

What does forward declaration do?

A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.


1 Answers

At least SQLAlchemy allows you to use a string instead of a class. Try if django-orm allows that, too.

a = models.ManyToManyField('A')
# ...
b = models.ManyToManyField('B')

Update: According to Django/Python Circular model reference that's exactly the way to go.

like image 53
ThiefMaster Avatar answered Sep 17 '22 19:09

ThiefMaster