loar
loar

Reputation: 1765

Set value in related model with ManyToManyField

I have these four models all related by ManyToManyFields:

A <--> B <--> C <--> D

Given an A object I need to set a value in its related field in D.

class A(models.Model):
    name = models.CharField()

    # Get all foo, from differents B, C and D
    @property
    def get_all_foo(self):
        for b in B.objects.filter(...):
            for c in C.objects.filter(...):
                foo = ';'.join([d.foo for d in D.objects.filter(...)])
        return foo

    def set_foo(self, value):
        # the code I need

class B(models.Model):
    a = ManyToManyField(A)

class C(models.Model):
    b = ManyToManyField(B)

class D(models.Model):
    c = ManyToManyField(C)
    foo = models.TextField()

What I need is to set the value of foo in D from a function in A (the same way I get all the values from it). How could I do it?

Upvotes: 0

Views: 53

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

Firstly, your get_all_foo method is incredibly inefficient, potentially causing thousands of separate database calls. Replace it with:

return ';'.join(D.objects.filter(c__b__a__=self).values_list('foo'))

You can use the same principle to update the D objects from A:

D.objects.filter(c__b__a__=self).update(foo=value)

Upvotes: 1

Related Questions