开发者

Django model class that can either have one relationship or another?

开发者 https://www.devze.com 2023-02-24 13:01 出处:网络
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 fi

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/Categ开发者_开发百科ory/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?


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:

class Department(models.Model):
    ...
    parent = models.ForeignKey('self', ...)

class Category(models.Model):
    ...
    parent_content_type = models.ForeignKey(ContentType)
    parent_id           = models.PositiveIntegerField()
    parent              = generic.GenericForeignKey('parent_content_type', 'parent_id')

This will allow you to represent an arbitrary tree of categories under an arbitrary tree of departments.


You could use django tree implementations django-mptt or django-treebeard

0

精彩评论

暂无评论...
验证码 换一张
取 消