[Answered ]-Having a django model which can belong to either of two other models (foreign key relation)

1👍

Forget about the SubFolders model.

You can simulate theese structures with a self-referenced relation in the CaseFolder model, checkout:

class CaseFolder(models.Model):
    name = models.CharField()
    parent = models.ForeignKey('self', blank=True, related_name='subfolders')

class Document(models.Model):
    file = models.FileField(upload_to=set_upload_path)
    belongs_to = models.ForeignKey(CaseFolder)

To know if a Document belongs to the root, just use document.belongs_to.parent is None.

1👍

To provide an alternative. You can use django-mptt.

pip install django-mptt

In your settings.py add mptt into the REQUIRED_APPS.

What this allows you to do is the following in your models:

from mptt.models import MPTTModel, TreeForeignKey

class CaseFolder(MPTTModel):
    name = models.CharField()
    parent = models.TreeForeignKey('self', blank=True, related_name='subfolder', db_index=True)

class MPTTMeta:
    order_insertion_by = ['name']

What this does on the database side is index the table to allow referencing between parent and child. This will (in theory) make your queries to the database easier and speed up your application as it grows. It also simplifies how the data is queried.

Leave a comment