2

I read about de/serializers but i couldn't find my way here. I have two apps, one where i store my data(scraped data) and another where i use the current/new data to display. I have identical models in these two apps. So i converted model of say app A to json and now i want to populate model of app B with that json . How might it be done? I didn't like to use django REST framework though.

so i did python manage.py dumpdata app_name > somefile.json

how do i populate fields of model B with the contents of somefile.json?

1 Answer 1

3

You can use model serializers. Lets say you have a model MyModel, create a serailizer for this model by,

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel

You will have to create a list with each element in the list as a dictionary of MyModel instance data. JSON data in python is basically a dictionary. So each element in your list will be dictionary (JSON data) for each unique instance of your model.

The list might look like:

[
    {
        "pk": "1",
        "field_1": "data_1",
        "field_2": "data_2",
        .....
    },
    {
        "pk": "2",
        "field_1": "data_1",
        "field_2": "data_2",
        .....
    },
    ...
]

Now pass the list with json data for MyModel to the serializer. If the json data is valid the serializer will deserialize the data into MyModel instances. Then you can simply save them.

serializer = MyModelSerializer(data=json_data, many=True)
if serializer.is_valid():
    serializer.save()  # `.save()` will be called on each deserialized instance
Sign up to request clarification or add additional context in comments.

1 Comment

This appears to be deprecated in Django 1.11 (serializers.ModelSerializer DNE)

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.