I have a small Django project where I get some information from an external source and use it to construct a model instance. The problem is that the source returns a lot (and I mean a lot!) of extra information which I don't need.
At the moment I am having to work out which extra records are in there and manually go through and delete each one. But this isn't very good because
If the external source changes, e.g. it adds a new field, my code will throw an error when I construct a model
myModel = MyModel(**argDict)
Is there a way I can pass an over-complete argDict
to my model and have it suppress any errors about extra information and just discard it? I was thinking that I could use a pre_init
signal but then I still didn't know how stop that error being given back.
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
A deferred attribute is an attribute that derives its value from an attribute value on a different account. You declare the deferred attribute in a view (and the WSUser model), and the provisioning engine performs this substitution immediately before calling the adapter.
According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.
The meta API provides a list of all available field instances via get_fields()
. You could write a utility function to filter kwargs for the init
:
def init_kwargs(model, arg_dict):
model_fields = [f.name for f in model._meta.get_fields()]
return {k: v for k, v in arg_dict.iteritems() if k in model_fields}
then,
kwars = init_kwargs(myModel, arg_dict)
myModel = MyModel(**kwargs)
will work for all models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With