Skip to content

Instantly share code, notes, and snippets.

@webjunkie
Created February 2, 2016 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webjunkie/ebe0fa52b5fb7fe7715f to your computer and use it in GitHub Desktop.
Save webjunkie/ebe0fa52b5fb7fe7715f to your computer and use it in GitHub Desktop.
Convert swagger to django model definition
import json
with open("swagger.json", "r") as f:
data = json.load(f)
def print_properties(value, pad=""):
properties = value.get('properties', {})
required = value.get('required', [])
for prop, prop_val in properties.items():
null = True
if prop == "type":
prop = "%s_type" % entity.lower()
s = "%s %s = models." % (pad, prop)
if prop_val.get('format') == "date-time":
s += "DateTimeField("
elif prop_val.get('type') == "number":
s += "DecimalField("
elif prop_val.get('type') == "integer":
s += "IntegerField("
elif prop_val.get('type') == "boolean":
s += "BooleanField("
null = False
elif prop_val.get('type') == "array":
s += "ManyToManyField(?, )"
elif prop_val.get('type') == "object":
s += "ForeignKey(?, "
if prop_val.get('properties'):
print_properties(prop_val, pad=pad+" ")
elif prop_val.get('$ref'):
s += "ForeignKey(%s, " % prop_val.get('$ref').replace("#/definitions/", "")
else:
s += "CharField(max_length=255, "
null = False
try:
for i in prop_val.get("items", {}).get("allOf", []):
if i.get('properties'):
print_properties(i, pad=pad+" ")
except AttributeError:
pass
if prop not in required:
if null:
s += "null=True, "
s += "blank=True"
s += ")"
print s.replace(", )", ")")
print
for entity, value in data['definitions'].items():
print "class %s(models.Model):" % entity
print_properties(value)
@webjunkie
Copy link
Author

Simple conversion of a swagger definition to Django model, in case one needs to store the data in the same way.

Still has some issues with nested elements, but already saves some work writing fields by hand.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment