Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 587
Pompeyo Avatar asked Sep 12 '13 08:09

Pompeyo


2 Answers

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.

like image 68
Peter DeGlopper Avatar answered Nov 02 '22 17:11

Peter DeGlopper


Yes, you can change values, but this is not how its done. Django Models are Python classes that have models to represent fields. For example a CharField is for holding a string in a database. Let me demonstrate (code from django docs):

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

As you can see above the Python class is a custom Django model. It is linked to a databse, and when you run manage.py syncdb, it will interact with your database to create the tables and columns that you need it to.

Now, in your case:

if my_model.is_changed:
    my_model.title = "Something"
    my_model.save()
like image 21
Games Brainiac Avatar answered Nov 02 '22 16:11

Games Brainiac