2

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?

Calum
  • 41
  • 1

2 Answers2

2

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.

Matt Howell
  • 15,750
  • 7
  • 49
  • 56
0

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

mossplix
  • 3,783
  • 2
  • 26
  • 31
  • I had a look at django-mptt. It looks like it helps a lot when using templates and views. Although I'm not sure how would this get around the problem of having a foreign key that points to one of two different classes, department or category. As far as I'm aware you'd need to combine these together when using mptt. – Calum Apr 14 '11 at 19:15