Relevant part of related classes:
class LineItems(models.Model):
status = models.CharField(max_length=10, null=True, blank=True, default="")
buch of other fields
class LineForecast(models.Model):
forecastamount = models.DecimalField(max_digits=10, decimal_places=2, default=0)
lineitem = models.OneToOneField(
LineItems, on_delete=models.SET_NULL, related_name="fcst", null=True
)
I would have been under the impression that if I wanted to update forecastamount based on field status of LineItems I could do something like:
lines_updated = LineItems.objects.filter(status="old").update(fcst__forecastamount=0)
There must be a simple thing I am not getting.
Hey there!
I suggest you to review the documentation on Queryset methods.
There you’ll find this section:
The update()
method is applied instantly, and the only restriction on the QuerySet
that is updated is that it can only update columns in the model’s main table, not on related models. You can’t do this, for example:
>>> Entry.objects.update(blog__name="foo") # Won't work!
Just after this section tells you that you can do the other way around (filtering on the related model, and updating on the main table).
In your case, that’s going to be:
LineForecast.objects.filter(lineitem__status="old").update(forecastamount=0)
Notice that instead of using the LineItems
class, it’s using the LineForecast
class, because this is the table that’s going to receive the update. We use the lineitem
reverse acessor to filter the status == “old”.
@leandrodesouzadev thanks for the pointer. Indeed, that solved the problem. I knew it had to be something simple.
1 Like