Build your models.py for django using script with json
2 min readJul 20, 2024
I had a issue lately where I had to scrap details from api and build django model so in order to record data I used following script that analyzed the response and gave me the models.py. This approach can be used to automate creating the whole flow for django as well. For more insights get connected.
a. main.py
import datetime
import json
def generate_model():
data = {}
with open("read.json") as file:
return json.load(file)
def get_last_var(value):
split_value = []
current_word = ""
for char in value:
if char.isupper() and current_word:
split_value.append(current_word)
current_word = char
else:
current_word += char
split_value.append(current_word)
return split_value[-1] if len(split_value) > 1 else split_value[0]
def generate_django_model(data, model_name="CashFlowStatement"):
with open("models.py", "w+") as file:
file.write("from django.db import models\n")
file.write(f"class {model_name}(models.Model):\n")
for key, item in data.items():
item = str(item)
try:
if "." in item or len(str(item)) > 4 or item[0] == "-":
item = float(item)
else:
item = int(item)
except Exception as e:
pass
if (
isinstance(item, datetime.date)
or key == "date"
or get_last_var(key) in ["date", "datetime", "Date", "DateTime"]
):
file.write(f" {key} = models.DateTimeField(null=True, blank=True)\n")
elif isinstance(item, float):
file.write(
f" {key} = models.DecimalField(max_digits=20, decimal_places=5, null=True, blank=True)\n"
)
elif isinstance(item, int):
file.write(f" {key} = models.IntegerField(null=True, blank=True)\n")
elif isinstance(item, bool) or item in ["True", "true", "false", "False"]:
file.write(f" {key} = models.BooleanField()\n")
elif isinstance(item, list):
file.write(f" {key} = models.ManyToManyField('self')\n")
elif isinstance(item, dict):
file.write(f" {key} = models.JSONField()\n")
else:
file.write(f" {key} = models.CharField(max_length=255,null=True, blank=True)\n")
print("models.py file generated successfully.")
data = generate_model()
generate_django_model(data)
# generate load_model
keys = data.keys()
def generate_load(keys):
with open("load_model.py", "w+") as file:
file.write("#load_data")
for key in keys:
file.write(f"{key}=item['{key}'],\n")
generate_load(keys)
b. example file
{'transcation_date':2024-2-2,
'name':'John Doe',
'description': 'John in Doe'}
Try it out .
If you are not using copilot or other things this can be helpful . But I recommend using copilot or other alternatives for coding . Since I dont use copilot I tried using this code to save my time.
Help yourself and me to improve .
Thanks .