codemastermind
codemastermind

Reputation: 344

one-to-many to many-to-many Relationship in Django model

I am looking for a relationship that

  1. A user creates an incident,
  2. Select multiple types
  3. And every type has many subtypes that users select from front-end

I have a table called the incident,

Incident 

name - XYZ
type - Multiple types
subtype - Multiple subtypes 

* Note
A type has many subtypes in the system

I am trying to do the below,

Incident
name -
type - M2M(Type)

Type
name -
subtype - M2M(Subtype)

Subtype
Name -

Please suggest if the below design is good to go. Thanks!

Upvotes: 1

Views: 289

Answers (1)

Metalgear
Metalgear

Reputation: 3457

You can design like the following. Here the Incident model can have the relations with SubType model because you can get the Type from the SubType model.

class Type(models.Model):
    name = models.CharField(max_length = 255)

class SubType(models.Model):
    name = models.CharField(max_length = 255)
    type = models.ForeignKey(Type, related_name = "sub_types", on_delete = models.CASCADE)

class Incident(models.Model):
    name = models.CharField(max_length = 255)
    sub_types = models.ManyToManyField(SubType)
    user = models.ForeignKey(User, related_name = "incidents", on_delete = models.CASCADE)

Upvotes: 2

Related Questions