I have a model:
class Vertex(models.Model):
pmap = models.ForeignKey('PMap',on_delete=models.CASCADE)
elevation = models.FloatField(default=0)
flow_sink = models.ForeignKey(
'Vertex',
on_delete=models.CASCADE,
related_name='upstream',
null=True)
And another model with the following function:
class PMap(models.Model):
def compute_flux(self, save=False):
vertices = self.vertex_set.order_by('-elevation').prefetch_related('flow_sink')
# Init flux
for vert in vertices:
vert.flux = 1.0 / len(vertices)
# Add flux from current to the downstream node.
for vert in vertices:
if vert.id != vert.flow_sink.id:
vert.flow_sink.flux = vert.flux
The function compute_flux()
is supposed to add the flux
value from the currently visited vertex to its flow_sink
(which in turn is another vertex). It should do this recursively, so that when it reaches a vertex that has had its flux
updated previously, it should yield that value to its own flow_sink
.
Sadly, this doesn't work. All vertices end up with the initial flux = 1.0 / len(vertices)
. I think the reason is that we're updating the vertices in the prefetched set prefetch_related('flow_sink')
rather than the vertices in the vertices
set. Thus vert.flux
in the last loop will never have any other value than the one set in the first (init) loop.
How can I fix this or work around the problem?