Use class before defining it in Django model
When I try to sync, I get an error. Menu is not a valid class name.
How can I solve this relationship case:
class MenuItem(model.Models)
title = models.CharField(max_length=200)
submenus = models.ManyToManyField(Menu, blank=True, null=True)
class Menu(Container):
links = models.ManyToManyField(MenuItem)
+3
source to share
2 answers
One of these models has many, many, the other uses Django reverse relationships (https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward)
So, how would I set it up:
class Menu(Container):
links = models.ManyToManyField(MenuItem)
class MenuItem(model.Models)
title = models.CharField(max_length=200)
Then when I wanted the MenuItem:
menu_item_instance.menu_set.all()
+6
source to share
From the Django book :
If you need to create a relationship on a model that has not yet been, you can use the model name rather than the model of the object itself:
eg:.
class MenuItem(model.Models)
title = models.CharField(max_length=200)
submenus = models.ManyToManyField('Menu', blank=True, null=True)
^ ^
Edit:
As Francis mentions (and as written in the documentation ):
It doesn't matter which model has a ManyToManyField, but you should only put it in one of the models - not both.
+7
source to share