[Answered ]-Return information from dict

2👍

✅

You can make this more generic with:

@classmethod
def create(cls, **kwargs):
    return cls(**{k: kwargs[k] for k in kwargs.viewkeys() & cls._meta.get_all_field_names()})

which filters the keyword arguments to just those for which there are fields.

Or just trust that no extra keyword arguments were passed in and use:

@classmethod
def create(cls, **kwargs):
    return cls(**kwargs)

If you also wanted the save the newly-created object (my_obj.save()) you could use the model.objects.create() method:

@classmethod
def create(cls, **kwargs):
    return cls.objects.create(**{k: kwargs[k] for k in kwargs.viewkeys() & cls._meta.get_all_field_names()})

or unfiltered:

@classmethod
def create(cls, **kwargs):
    return cls.objects.create(**kwargs)

Leave a comment