Parsing static json file and save values to Django Database/model

六月ゝ 毕业季﹏ 提交于 2020-03-26 03:55:06

问题


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:


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'], 
         ) 


来源:https://stackoverflow.com/questions/57237900/parsing-static-json-file-and-save-values-to-django-database-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!