I have a model form that saves all form field inputs to the backend database as one entry. I also have a JSON file that contains multiple JSON objects whose fields corresponds to the model form field. This JSON file is being uploaded via FileField in the model. Ultimately, I want to be able to upload a JSON file with the multiple JSON objects into my model form and populate the fields with the corresponding values from the uploaded JSON file. Each JSON object will be a single entry to my database and they can have null values for at least one field. Ideally, I would like to be able to choose which JSON object (from the uploaded JSON file) gets loaded to my model form fields to eventually be saved in my database. How would I go about implementing this?
Asked
Active
Viewed 1,302 times
2 Answers
1
To unpack a JSON string into a Django model, you can use the Python Standard Library json
package to convert it into a dict
and then unpack it into the object as keyword arguments using **
:
>>> from user.models import User
>>> import json
>>> some_json = '{"username": "cole","password": "testing123"}'
>>> User(**json.loads(some_json))
<User: cole>
>>> User(**json.loads(some_json)).username
'cole'
>>> User(**json.loads(some_json)).password
'testing123'
By the way, there's a nice StackOverflow answer about **
here.

Cole
- 1,715
- 13
- 23
0
You could use the django rest framework. It will provide a post function and serializers.
You'll wind up with some stuff like this:
# the model
class Book(Model):
title = TextField()
author = TextField()
# the serializer
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
# the view
class BookView(generics.ListCreateApiView):
queryset = Book.objects.all()
serializer_class = BookSerializer
see the tutorial for more details: http://www.django-rest-framework.org/tutorial/1-serialization/#tutorial-1-serialization
Then you can post your data to the database
data = [{'title': 'Moby Dick', 'author': 'Herman Melville'},
{'title': 'A Game of Thrones', 'author': 'George R. R. Martin'}]
for d in data:
r = requests.post('django_api_url/book/', d)
r.raise_for_status()
# the new record is returned if successful
print(r.json())

Jonah
- 727
- 5
- 12