Reputation: 53
How to design a model in django for storing below JSON values in a single model
class Bus(models.Model):
source = models.CharField(max_length=200)
destination = models.CharField(max_length=200)
type= models.CharField(max_length=200)
price=models.FloatField()
I need to accept below json to accept and store in same table if i can use ListField , then how it will be for connections
{
"source": "delhi",
"destination": "pune",
"type": "Economy",
"price":300.0,
"Connections": [
{
"source": "lon",
"destination": "liverpool",
"type": "luxury",
},
{
"source": "banglur",
"destination": "cochin",
"type": "luxury",
}
],
}
Upvotes: 0
Views: 31
Reputation: 674
You could use Foreign Keys.
from django.db import models
class Connection:
source = models.CharField(max_length=256)
destination = models.CharField(max_length=256)
type = models.CharField(max_length=256)
class Bus(models.Model):
source = models.CharField(max_length=256)
destination = models.CharField(max_length=256)
type = models.CharField(max_length=256)
price = models.FloatField()
connections = models.ForeignKey(Connection, on_delete=models.CASCADE)
Or JsonField.
from django.contrib.postgres.fields import JSONField
from django.db import models
class Bus(models.Model):
source = models.CharField(max_length=256)
destination = models.CharField(max_length=256)
type = models.CharField(max_length=256)
price = models.FloatField()
connections = JSONField()
Upvotes: 1