I have these models the for django and django-rest framework.
class ProductType(models.Model):
name = models.CharField(max_length=30)
class Product(models.Model):
name = models.CharField(max_length=100)
type = models.ForeignKey(ProductType)
class Category(models.Model):
name = models.CharField(max_length=50)
class Attribute(models.Model):
name = models.CharField(max_length=50)
type = models.ForeignKey(ProductType)
category = models.ForeignKey(Category)
Model objects are saved like
Product Type
[{"id" : 1, "name": "Type A"},
{"id" : 2, "name": "Type B"}]
Platform
[{"id" : 1, "name": "Product A", "type": 1},
{"id" : 2, "name": "Product B", "type": 2}]
Category
[{"id" : 1, "name": "Category A"},
{"id" : 2, "name": "Category B"},
{"id" : 3, "name": "Category C"}]
Attribute
[{"id" : 1, "name": "Attribute A", "category":1, "type": 1},
{"id" : 2, "name": "Attribute B", "category":1, "type": 2},
{"id" : 3, "name": "Attribute C", "category":1, "type": 1},
{"id" : 4, "name": "Attribute D", "category":1, "type": 1},
{"id" : 5, "name": "Attribute E", "category":2, "type": 1},
{"id" : 6, "name": "Attribute F", "category":2, "type": 1},
{"id" : 7, "name": "Attribute G", "category":2, "type": 2},
{"id" : 8, "name": "Attribute H", "category":3, "type": 2},
{"id" : 9, "name": "Attribute I", "category":3, "type": 2}]
and I want to get a Product object with PK=1 as described below
{
"id": 1,
"name": "Product A",
"type": 1,
"categories": [
{
"id": 1,
"name": "Category A",
"attributes": [
{
"id": 1,
"name": "Attribute A"
},
{
"id": 2,
"name": "Attribute C"
},
{
"id": 4,
"name": "Attribute D"
}
]
},
{
"id": 2,
"name": "Category B",
"attributes": [
{
"id": 5,
"name": "Attribute E"
},
{
"id": 6,
"name": "Attribute F"
}
]
}
]
}
Currently, I am querying each of the models, then reorganize results in the client as I desire.
However, I would like to do the same tasks in the server side to make the client code simple.
Notice, Platform and Category are not directly related.