Created
October 6, 2022 07:07
-
-
Save MarkusH/1702363bcb9ace29b65915900b17e153 to your computer and use it in GitHub Desktop.
Print plantuml instructions for an ER diagram of all Django models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.apps import apps | |
HEADER = """@startuml | |
skinparam linetype ortho | |
""" | |
FOOTER = """@enduml""" | |
Models = apps.get_models() | |
def format_model(M): | |
return f'"{M._meta.app_label}.{M.__name__}"' | |
print(HEADER) | |
for Model in Models: | |
model_ref = format_model(Model) | |
print("entity %s {}" % model_ref) | |
for Model in Models: | |
model_ref = format_model(Model) | |
for field in Model._meta.fields: | |
if field.is_relation: | |
RelatedModel = field.related_model | |
related_model_ref = format_model(RelatedModel) | |
if field.one_to_one: | |
if field.null: | |
rel_string = "|o--o|" | |
else: | |
rel_string = "||--o|" | |
# elif field.one_to_many: | |
# pass | |
elif field.many_to_one: | |
if field.null: | |
rel_string = "}o--o|" | |
else: | |
rel_string = "}|--o|" | |
elif field.many_to_many: | |
rel_string = "}o--o{" | |
else: | |
print("ERROR") | |
continue | |
print(f"{model_ref} {rel_string} {related_model_ref}") | |
print(FOOTER) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment