I have a file in json format, with such a structure:
{
"Admiralty Islands": [
[
"Up to 1 kg",
"5.00"
],
[
"1 - 10 kg",
"10.00"
],
],
"Afghanistan": [
[
"Up to 1 kg",
"15.00"
],
[
"1 - 10 kg",
"20.00"
],
],
...
}
And a three models:
class Country(models.Model):
name = models.CharField(max_length=128, unique=True)
class Weight(models.Model):
name = models.CharField(max_length=128, unique=True)
min_weight = models.IntegerField()
max_weight = models.IntegerField()
class Shipping(models.Model):
country = models.ForeignKey(Country)
weight = models.ForeignKey(Weight)
price = models.DecimalField(max_digits=7, decimal_places=2)
What is the most correct way to import to the database using a json file?
Should I convert the json file into fixture file? But what to do with relationships between tables?
Or is it better to write the view
like:
f = open('file.json', 'r')
obj = simplejson.load(f)
for o in obj:
record = Country(name = o)
record.save()
But also can not figure out how to make relations between the models
.
Or is there an easier way?
Thanks.
I don't see a very clear structure in your json in a sense that it is not explicitly defined anywhere which field should go into which model and how everything is related. So I would recommend just to make an import script in which manually go through all of the json and create the proper model instances.
A good example in my opinion of well structured json is the output of the Django serialization. You can take a look at it here.
Well for data in json
to be populated to database:
You need to map the data fields from json to the database.
The best and the preferred or rather the designed way of doing this is to do use fixtures.
For mapping Django Serialization is the way to GO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With