使用JSON创建模型对象-Django [英] Use JSON to create Model objects - Django

查看:60
本文介绍了使用JSON创建模型对象-Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含JSON的外部URL.

I have an external URL containing JSON.

所以我的问题是:如果我创建了以下与JSON键匹配的模型,如何将JSON数据保存到Django管理页面中?

So my question is: How do I save the JSON data to my Django admin page if I created the following model that matches the Keys of the JSON?

from django.db import models

class Person(models.Model):

    name = models.CharField(max_length=254)
    image_url = models.ImageField(blank=True)
    title = models.CharField(max_length=254)
    bio = models.CharField(max_length=20000)
    vote = models.IntegerField()

我的目标是能够创建一个投票应用程序,让您为JSON定义的每个人投票.

My goal is to be able to create a voting app that lets you vote for each individual person defined by the JSON.

这是此问题的较长版本: https://stackoverflow.com/questions/46149309/create-object- models-from-external-json-link-django

Here is the longer version of this question: https://stackoverflow.com/questions/46149309/create-object-models-from-external-json-link-django

推荐答案

我能够通过运行以下命令来弄清楚它:

I was able to figure it out by running the following:

import json
from rest_framework.views import APIView
from rest_framework.response import Response
from urllib.request import urlopen
from .models import Person
from .serializers import PersonSerializer


class PersonView(APIView):

    def get(self, request):
        data = urlopen("<JSONURLHERE>").read()
        output = json.loads(data)
        persons = Person.objects.all()
        serializer = PersonSerializer(persons, many=True)
        for person in output:
            if person['id'] not in [i.id for i in persons]:
                Person.objects.create(id=person['id'], name=person['name'], image_url=person['image_url'],
                                          title=person['title'], bio=person['bio'])
        return Response(serializer.data)

我基本上是在使用JSON创建对象的地方.

Where I'm basically creating objects using the JSON.

这篇关于使用JSON创建模型对象-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆