1👍
✅
You don’t, or at least not without applying "tricks" to "translate" the method into a database expression.
In this specific case, we probably have a dictionary lookup, so we can do this with:
from django.db.models import Case, Value, When
queryset = Model1.objects.annotate(
organization_name=Case(
*[
When(polis_journal__organization_id=k, then=Value(v))
for k, v in polis_organizations.items()
],
default=Value(None)
)
)
but not only is this ugly, and will this result in a large expression, it will perform dictionary lookups in linear time.
Usually one just stores the name of the organization in a model:
class Organization(models.Model):
name = models.CharField(max_length=128, unique=True)
class Model2(models.Model):
# …
organization = models.ForeignKey(Organization, on_delete=models.PROTECT)
and then we can thus work with:
Model1.objects.annotate(organization_name=F('polis_journal__organization__name'))
Source:stackexchange.com