I created a model class and a method that saves Json data to that model.
models.py:
class Object(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
@classmethod
def save_json_data_to_model(cls):
with open('data.json', encoding='utf8') as file:
data = json.load(file)
for obj in data:
Object(
name=obj['name'],
address=obj['Street']).save()
I want the json data to be populated in the model automatically and not call the method "save_json_data_to_model(cls)" manually. What is the best way to achieve this?
I tried something like this:
views.py:
if __name__ == '__main__':
Obj.save_json_data_to_model()
You should make this a data migration: https://docs.djangoproject.com/en/2.1/topics/migrations/#data-migrations