In views.py I have:
my_computer = Computer.objects.get(pk=some_value)
The computer object has a field called projects that's a ManyRelatedManager.
Calling
my_projects = my_computer.projects.all()
will set the value of my_projects to a list of three project objects.
What I'm trying to achive is to set the value of my_computer.projects to the above list of projects instead of the ManyRelatedManager.
I have tried:
my_computer.projects = my_projects
but that doesn't work, although it doesn't raise an error either. The value of my_computer.projects is still the ManyRelatedManager.
Managerobjects implement__set__- they behave as descriptors.This means you cannot change the object by assigning it (as long as its attribute of another object -
__set__is only called in the context of__setattr__on the parent object - parent regarding composition relationships, and not inheritance relationships).You can assign any list-like (actually: iterable) value to a manager if such iterable value yields models of the expected type. However this means:
my_computer.projects, you will get again a manager object, with the objects you assigned.my_computer, only the specified objects will belong to the relationship - previous object in the relationship will not be related anymore to the current object.There are three scenarios you could have which led you to this issue:
You need to hold a volatile list - this data is not stored, in any way, but used temporarily. You have to create a normal attribute in the class:
You need another representation of the exact same relationship - in this way, you want a comfortable way to access the object, instead of calling a strange .all(), e.g. to do a
[k.foo for k in mycomputer.my_projects]. You have to create a property like this:You need another relationship (so it's not volatile data): Create ANOTHER relationship in your model, pointing to the same mode, using the same
throughif applicable, but using a different related_name= (you must explicitly set related_name for at least one of the multiple relationships to the same model, from the same model)