0

I have an external URL containing JSON.

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()

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

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

2 Answers 2

1

If I understand your question correctly you can use Model serializers for this end.

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person

And then you can use this PersonSerializer to populate the model with your person_json objects (in this case in an array of json objects) which you get from the REST API.

personSaver = PersonSerializer(data=person_json, many=True)
if personSaver.is_valid():
    personSaver.save()
Sign up to request clarification or add additional context in comments.

1 Comment

I will try this, and let you know. I'm trying to create objects from a JSON file, so I can pass it into my HTML, and I want to be able to see the objects that were created based on this JSON, in my Admin page.
1

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)

Where I'm basically creating objects using the JSON.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.