Search code examples
pythondjangomodels

How to assign items inside a Model object with Django?


Is it possible to override values inside a Model? I am getting 'MyModel' object does not support item assignment.

my_model = MyModel.objects.get(id=1)
print my_model.title

if my_model.is_changed:
    my_model['title'] = 'something' # 'MyModel' object does not support item assignment

params = {
        'my_model': my_model,
         ...
    }
return render(request, 'template.html', params)

Solution

  • Models are objects, not dictionaries. Set attributes on them directly:

    if my_model.is_changed:
        my_model.title = 'something'
    

    Or, if the attribute name is dynamic, use setattr:

    attr_name = 'title' # in practice this would be more complex
    if my_model.is_changed:
        setattr(my_model, attr_name, 'something')
    

    This changes the in-memory copy of the model, but makes no database changes - for that your attribute would have to be a field and you'd have the call the save method on my_model. You don't need to do that if you just want to change what the template receives in its context, but just for completeness's sake:

    if my_model.is_changed:
        my_model.title = 'something'
        my_model.save()
    

    Dictionaries are mutable, if you actually have a dictionary:

    mydict = {'title': 'foo'}
    # legal
    mydict['title'] = 'something'
    

    But not everything is a dictionary.