在Django模型中定义之前使用类 [英] Use a class before its definition in Django model

查看:50
本文介绍了在Django模型中定义之前使用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试同步数据库时,出现错误菜单不是有效的类名称.

When I try to syncdb I get the error Menu is not a valid class Name.

我该如何解决这种情况:

How can I resolve that 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)

推荐答案

来自 Django书:

如果需要在尚未创建的模型上创建关系定义后,您可以使用模型的名称,而不是模型对象本身:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

例如:

class MenuItem(model.Models)
    title = models.CharField(max_length=200)
    submenus = models.ManyToManyField('Menu', blank=True, null=True)
                                      ^    ^


正如 Francis提到的(如

哪个模型具有ManyToManyField无关紧要,但是您应该只将其放在其中一个模型中,而不要同时放在两个模型中.

It doesn't matter which model has the ManyToManyField, but you should only put it in one of the models -- not both.

这篇关于在Django模型中定义之前使用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆