Stack Exchange
Unknown output_field type in Subquery in Django
I have the following models:
class Parent1(models.Model):
    name = models.CharField(max_length=255)

class Parent2(models.Model):
    parent1 = models.ForeignKey(Parent1)
    label = models.CharField(max_length=255)

class Child(models.Model):
    parent1 = models.ForeignKey(Parent1)
    parent2_label = models.CharField(max_length=255)
    # other fields

I am trying to execute the below queries:
parent1 = Parent1.objects.first()
sq = Child.objects.filter(
    parent1=OuterRef("parent1"), parent2_label=OuterRef("label")
)
parents_2 = Parent2.objects.filter(parent1=parent1).annotate(
    children=Subquery(sq)
)

So basically what I am trying to execute is if Child model had a fk to Parent2 then I would have prefetched the related child instances of the Parent2 instances. Now at present there is no fk relation between Child and Parent2. The relation is based on the label field between those two. fk will be added later but before that for backwards compatibility I have to execute this query.
Now when I try to execute this query then I am getting the following error:
FieldError: Cannot resolve expression type, unknown output_field

I am using Postgresql db. Now what will be the output_field for the above query that I have to pass?
So basically what I am trying to achieve through the subquery is this:
# this is not a working example.
parents_2 = Parent2.objects.filter(parent1=parent1)
for parent in parents_2:
    children = Child.objects.filter(parent1=parent1, parent2_label=parent.label)
    parent.annotate(children=children)

I want the children to be a nested object with each parent_2 in the queryset.

Do you expect the annotation children to return a queryset of all the children of that parent? I don't see how that could be possible: https://stackoverflow.com/questions/44783587/how-to-annotate-django-queryset-with-other-object-using-subquery You could use ArrayAgg to have the subquery return an array of children IDs, or something similar.

Yes. For each parent2, I want children to be a list of dicts of the related child instances. Relation meaning child instances that have parent1 fk and parent2 labels of that parent2 instances.

@CoffeeBasedLifeform I have added an example code. Is it possible to achieve without looping and using a subquery?

I don't think so, no. Try to picture how the result of the query would look like in Postgres; the children annotation is just a single column in that result table, so the annotation must be a single value of a Postgres data type. When building a query with Django, you can declare the type of the column with the output_field argument of an expression. But there is no output_field for Django querysets, model instances or python dictionaries, so you can't have the result of the annotation be of those types.
