1👍
You have a few options.
- Load the data into a model that matches the json, if it’s consistent for each record.
- Load the data into a JSON field on a django model.
- Just use a comprehension to filter your dicts.
For (3), once you’ve loaded the JSON into a list of python dicts you can manipulate it.
So:
- Count the records:
len(comments_data)
- All the records:
comments_data
- Filter the records:
[item for item in comments_data if item["email"] == "Eliseo@gardner.biz"]
etc.
Basically, there’s no need to try and replicate ORM stuff here.
There are a couple of options to load data into Django models:
-
Treat the data as fixtures: https://docs.djangoproject.com/en/4.1/howto/initial-data/
-
Deserialize the data yourself: https://docs.djangoproject.com/en/4.1/topics/serialization/
At the very basic level, if you have a model that matches a json record, you can create an instance and then save it. eg.
# You have the model
class TestModel(models.Model):
field_one = CharField(...)
field_two = IntegerField(...)
# And the JSON:
json_data = {
"field_one": "This is the first rec",
"field_two": 1,
}
# You can create an instance of the model class and save it
instance = TestModel(**json_data)
instance.save()
For more information on translating json into django models and vice-versa, I suggest you read up on serializers.
Source:stackexchange.com