python - Return information from dict -
i want save object minimum of code.
in views (need specific attributes):
my_obj = entry.create(name=my.name, ...)
in models:
@classmethod def create(cls, **kwargs): return cls(name=kwargs['name'], ...)
is there way shorten code? provide examples.
you can make more generic with:
@classmethod def create(cls, **kwargs): return cls(**{k: kwargs[k] kwargs.viewkeys() & cls._meta.get_all_field_names()})
which filters keyword arguments there fields.
or trust no keyword arguments passed in , use:
@classmethod def create(cls, **kwargs): return cls(**kwargs)
if wanted save newly-created object (my_obj.save()
) use model.objects.create()
method:
@classmethod def create(cls, **kwargs): return cls.objects.create(**{k: kwargs[k] kwargs.viewkeys() & cls._meta.get_all_field_names()})
or unfiltered:
@classmethod def create(cls, **kwargs): return cls.objects.create(**kwargs)
Comments
Post a Comment