'How to manage and save nested arrays to django models
I'm receiving the data from the frontend app in the form of Arrays, or say List of objects. I want to create and save the data using Django models and views. I'm a little confused about how can make a structure of tables to save this type of data That's how would be I receiving data:
[
{ question: 'Screen Works Properly', parentId: 1, child: [] },
{
question: 'Theres issue of Hardware',
parentId: 2,
child: [
{ id: 15, sub_question: 'Broken Speakers' },
{ id: 18, sub_question: 'Battery Damaged' }
]
}
]
There could an unlimited number of objects in the list and every object has a child array which can have an unlimited number of objects as well.
I can see there I can make a model Data and then can link the objects with ForeignKey, But how will I manage the child Array/list in the object. Can anybody give me an idea of how can I create models to save this type of data?
That's my try :
class Data(models.Model):
order = models.OneToOneField(
PickupOrder, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.id
class Question(models.Model):
question = models.ForeignKey(
Data, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.id
class Child(models.Model):
child = models.OneToOneField(
Question, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.id
class SubQuestion(models.Model):
sub_question = models.ForeignKey(
Child, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.id
Do u think that is the proper way to manage it? Or there can be some flaws or any better way to approach this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
