Django 模型类可以具有一种关系或另一种关系?
为了让您了解我正在尝试解决的问题,我将使用一个示例。问题在于类之间可能存在多种可能的关系,以及如何在模型文件中表示这种关系。在购物网站中,部门可以具有子部门或类别关系。理论上,这意味着一个部门可以有 100 个子部门,直到它有一个类别。
例如部门/类别/项目、部门/部门/类别/类别/项目、部门/类别/类别/项目...等
我的问题是如何最好地在 Django models.py 文件中描述这种关系?您是否只有两个外键,其中一个为空?
To give you an idea of the problem I'm trying to solve I'll use an example. The issue is that there can be multiple possible relationships between classes, and how to represent this in the models file. In a shopping website the Department can either have a Sub-Department or a Category relationship. This can theoretically mean that one Department could have 100 sub departments until it has a category.
e.g. Department/Category/Item, Department/Department/Category/Category/Item, Department/Category/Category/Item...etc
My question is how best to describe this relationship in the Django models.py file? Would you just have two foreign keys and one would be empty?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将在您的类别和部门模型上创建一个父属性,以便您可以表示层次结构。
您可以在部门模型上使用外键以允许它们指向其他部门,并且您可以使用 GenericKey 在类别模型上,以允许其指向部门或其他类别。例如:
这将允许您在任意部门树下表示任意类别树。
I'd create a parent attribute on your Category and Department models, so that you can represent the hierarchical structure.
You can use a ForeignKey on the Department model to allow them to point to other Departments, and you can use a GenericKey on the Category model to allow it to point to Departments or other Categories. For example:
This will allow you to represent an arbitrary tree of categories under an arbitrary tree of departments.
您可以使用 django 树实现 django-mptt 或 django-treebeard
You could use django tree implementations django-mptt or django-treebeard