____ _ ____
/ ___|___ | |__ _ __ __ _ / ___| ___ _ __
| | / _ \| '_ \| '__/ _` | | _ / _ \ '_ \
| |__| (_) | |_) | | | (_| | |_| | __/ | | |
\____\___/|_.__/|_| \__,_|\____|\___|_| |_|
Some of the best parts of being a polyglot developer are being able to combine your favorite languages in practical ways.
At my current job, I haven’t had many opportunities to use Scala until recently. Even if I wanted to, I can’t (and shouldn’t) force my language preferences on my teammates. What I can do is build tooling that benefits everyone.
That’s usually how these projects start: small tools to make my own life easier.
We’ve been using Django quite a bit, and I found myself writing the same model boilerplate over and over. So I built Cobragen, a small CLI tool that generates a models.py file from a YAML schema definition.
Usage
Make a yaml file with your models schema, like this:
models:
- name: UserProfile
fields:
- name: username
type: Char
maxLen: 50
unique: true
- name: bio
type: TextField
required: false
- name: age
type: Integer
- name: balance
type: Decimal
maxDigits: 12
places: 2
- name: created_at
type: DateTime
- name: is_verified
type: Boolean
- name: Post
fields:
- name: author
type: ForeignKey
to: UserProfile
onUpdate: CASCADE
- name: title
type: Char
maxLen: 200
- name: content
type: TextField
- name: published_date
type: Date
required: false
then run:
cobragen <schema.yml> [--sort] [--name <output>]
-
--sort— sort models alphabetically by name before generation (default:false) -
--name <filename>— custom output filename (default:models.py)
This will generate a .py file with your models:
from django.db import models
class Post(models.Model):
author = models.ForeignKey("UserProfile", on_delete=models.CASCADE)
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateField(null=True, blank=True)
class UserProfile(models.Model):
username = models.CharField(max_length=50, unique=True)
bio = models.TextField(null=True, blank=True)
age = models.IntegerField()
balance = models.DecimalField(max_digits=12, decimal_places=2)
created_at = models.DateTimeField()
is_verified = models.BooleanField()
It has its lil problems, but I can live with them. It has partial feature support and covers what I currently need; it was a nice exercise in schema modeling and code generation across ecosystems.
Top comments (0)