Home > Back-end >  How to relate a table to multiple other tables while still having one-to-many relationship?
How to relate a table to multiple other tables while still having one-to-many relationship?

Time:04-20

Let's say I have the following model classes:

# Inspection target
class Target(models.Model):
    ...

# Issue found during the inspection
class Issue(models.Model):
    target = models.ForeignKey(Target, on_delete=models.CASCADE, related_name='issues')

So, a Target can have multiple related Issues, while an Issue always relates to one Target. Now, let's say I add a new table like this:

# Document that describes either a target or an issue
class Document(models.Model):
    ...

... and I want this both Targets and Issues to have references to Documents, but a single Document can only be related to one object, either a Target or an Issue. Is this possible to do with Django?

CodePudding user response:

Yes, your definition of Target and Issue is fine for what you want. A Target can have multiple Issue, where an Issue can have only relation with a single Target.

Now you want, Target and Issue to refer to Document. For this your models.py will look like this.

class Document(models.Model):
    ...
    target = models.ForeignKey(Target, related_name='target_documents', on_delete=models.CASCADE, null=True, blank=True)
    issue = models.ForeignKey(Issue, related_name='issue_documents', on_delete=models.CASCADE, null=True, blank=True)
    ...

And then, the rest you have to handle in your views.py where you have to allow only one value either Target or Issue.

  • Related