django-any
django-any copied to clipboard
Use defaults from model where available
Having used django-any in a couple of projects i strongly prefer to fill fields with sane values from model classes instead of weird stuff.
Don't know where to put this so here's just some code instead of fork/PR:
def lazy_model(cls, **attrs):
"""Use model-provided defaults"""
from django.db.models.fields import NOT_PROVIDED
from inspect import isfunction, ismethod
for field in cls._meta.fields:
default = field.default
if default is not NOT_PROVIDED:
if isfunction(default) or ismethod(default):
# for stuff like default=datetime.now
default = default()
attrs.setdefault(field.name, default)
return any_model(cls, **attrs)
Nice function for contrib package, not sure about the name, may be any_model_with_defaults will be more convinient
Yeah, i was too lazy to name it properly (=