Parsing static json file and save values to Django

2019-08-20 04:32发布

I have json file in my static folder in my django project. And I want to save the data from json file to my Django Database.

This is my model.py

from django.db import models


class Coming_Soon(models.Model):
    movie_id = models.CharField(primary_key=True, max_length=11)
    movie_title = models.TextField(blank=True, max_length=100)
    image_url = models.TextField(blank=True)
    synopsis = models.TextField(blank=True)
    rating = models.TextField(default="MTRCB rating not yet available")
    cast = models.TextField(blank=True)
    release_date = models.TextField()

this is sample of my json file

{
  "results": [
    {
      "rating": "PG",
      "cast": [
        "Jeremy Ray Taylor",
        "Gerard Butler",
        "Abbie Cornish"
      ],
      "synopsis": "some synopsis",
      "movie_title": "(3D/4DX) GEOSTORM",
      "image_url": "some url",
      "id": "8595"
    },
    {
      "rating": "PG",
      "cast": [
        "Jeremy Ray Taylor",
        "Gerard Butler",
        "Abbie Cornish"
      ],
      "synopsis": "some synopsis",
      "movie_title": "(ATMOS) GEOSTORM",
      "image_url": "some url",
      "id": "8604"
    }
  ]
}

what should I write on my view so that I can save those data into my django database? This is my views.py:

def polls(request):
    ROOT_FILE = STATIC_ROOT + '/polls/coming_soon.json'
    json_data = open(ROOT_FILE)
    json_load = json.load(json_data)

    with open(ROOT_FILE, 'r') as data:
        parsed_json = json.load(data)

        for result in parsed_json['results']:
    # HOW CAN I SAVE DATA INTO DATABASE??

I really don't have any idea about getting those file into my database. Thank you.

1条回答
Root(大扎)
2楼-- · 2019-08-20 05:10

You can create obj like this

from .models import Coming_Soon
   def polls(request):

    ROOT_FILE = STATIC_ROOT + '/polls/coming_soon.json'
    json_data = open(ROOT_FILE)
    json_load = json.load(json_data)

    with open(ROOT_FILE, 'r') as data:
    parsed_json = json.load(data)

    for result in parsed_json['results']:
        Coming_Soon.objects.create(
           movie_id = result['id'],
           movie_title = result['movie_title'],
           image_url=result['image_url'],
           synopsis = result['synopsis'], 
         ) 
查看更多
登录 后发表回答