[Django]-How to update dynamically a model in Django?

3๐Ÿ‘

โœ…

If you are trying to create new instances of your model from each row of the data, use the setattr function to set the values:

data=np.genfromtxt("file.csv", delimiter=',', dtype=None, names=True)
columns = data.dtype.names
for i in range(len(data['id'])):
    p = MyModel()
    for a in range(1, len(columns)): #1
        if hasattr(p, columns[a]):
            setattr(p, columns[a], data[i][columns[a]])
        else:
            raise AttributeError("'MyModel' object has no attribute '{0}'".format(columns[a]))
    p.save()
๐Ÿ‘คBlair

1๐Ÿ‘

You could consider constructing a dictionary of the arguments you want to pass, and then use ** to supply the dictionary to the function as those arguments.

column_args_dict = {columns[a]: data[i][columns[a]]}
p = MyModel.objects.filter(**column_args_dict)
๐Ÿ‘คSoylentFuchsia

Leave a comment