[Answered ]-Is it possible to use Django ORM with JSON object?

1👍

You have a few options.

  1. Load the data into a model that matches the json, if it’s consistent for each record.
  2. Load the data into a JSON field on a django model.
  3. 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:

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.

Leave a comment