Django model update multiple instances with custom Manager function

199 Views Asked by At

I have a model class (for example A) inside the Django model framework. For this model I have created his Manager class with some functions.

class T_Manager(BaseModelManager):

    def add_function(value):
        ....

class T(BaseModel):
    objects = T_Manager()
    ....


class A(BaseModel):
    t = GenericRelation('T', related_name='t')
    ....

Now I have a list of A class objects and I would like to call add_function on all of them efficiently.

I would like to use something like

list_a.update(F('add_function', value))

or something like this.

Is there a way to call this function inside the update function or what is recommended way to do this?

1

There are 1 best solutions below

1
mirodil On

It is not possible to call the add_function() method of T_Manager class inside update() method of A model.

To call add_function() on all T instances related to the A objects you can use loop to iterate through T objects:

for a in list_a:
    for t in a.t.all():
        t.objects.add_function(value)

or use custom manager to iterate all related T objects:

class A_Manager(BaseManager):
    def update_related_t(self, value):
        for a in list_a:
            for t in a.t.all():
                t.objects.add_function(value)

you can then call custom manager:

A.objects.update_related_T(value)