django-any icon indicating copy to clipboard operation
django-any copied to clipboard

Use defaults from model where available

Open dpwiz opened this issue 14 years ago • 2 comments

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)

dpwiz avatar May 12 '11 13:05 dpwiz

Nice function for contrib package, not sure about the name, may be any_model_with_defaults will be more convinient

kmmbvnr avatar May 13 '11 01:05 kmmbvnr

Yeah, i was too lazy to name it properly (=

dpwiz avatar May 13 '11 04:05 dpwiz