Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ignore extra arguments on constructing model

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

  1. It makes for very ugly code and
  2. 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.

like image 376
JMzance Avatar asked Mar 02 '16 11:03

JMzance


People also ask

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

What does null true mean in Django?

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.

What is deferred attribute Django?

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.

What is AutoField in Django?

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.


1 Answers

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.

like image 90
user2390182 Avatar answered Sep 16 '22 20:09

user2390182