Django 3-Tier Nested Modeling
I have a problem where I need a deeply nested model. I have a model named Theme (it's called something else), and in theme I can have many Types. In a Type I can have many or none SubTypes. In a SubType I can have many or none Additionals.
The JSON Structure would be like so:
{
"id": 5,
"name": "test-theme",
"types": [
{
"type_id": 101,
"value": "test-type",
"subtypes": [
{
"subtype_id": 101,
"value": "test-subtype",
"additionals": [
{
"additional_id": 101,
"value": "test-additional"
}
]
}
]
}
]
}
What I've done so far:
I've setup my core models -> Type, SubType, and Additionals. Since, these models will be defined and immutable.
Then I've setup my models to create the user defined theme context. This is the only time where a type has subtypes, a subtype has additionals.
An example of how I set it up:
class Theme(models.Model):
"""
...
"""
name = models.CharField(max_length=100, unique=True)
...
class ThemeTypeBridge(models.Model):
"""
...
"""
theme = models.ForeignKey(Theme, related_name="types", on_delete=models.CASCADE)
type = models.ForeignKey(Type, related_name="theme_links", on_delete=models.CASCADE)
...
The 3-tier nested data:
Theme
- ThemeTypeBridge
- ThemeSubTypeBridge
- ThemeAdditionalBridge
I'm having trouble with writable serializers in django, since I have a main model that has a bunch of additional nested models. Theme being one of them. This main model, modelA, has a writable serializer. Though, I'm having issues with this error:
{"types":[{"type":["Incorrect type. Expected pk value, received Type."],"subtypes":[{"subtype":["Incorrect type. Expected pk value, received Subtype."],"additionals":[{"additional":["Incorrect type. Expected pk value, received Additional."]}]}]}]}
I guess my question is, how do I properly model a 3 tier data model in django models and serializers?