Improve the query structure or how can i use prefetch related

I have a situation and I'm not able to think of how to use prefetch_related or improve the structure of my query, here is the scenario -

rows = DocumentRows.objects.filter(item=item_id).values_list("document", flat=True)
qs = Document.objects.filter(id__in = rows)

return qs

Document contains ID and other imp related info, Document is linked to DocumentRows as a foreign key, and is of type one-to-many Relationship. Each Document can have multiple rows and each row contain item (item_id).

I'm trying to filter document based on items present in document rows.

Thanks

You didn't share models/DB schema structure, so the below is an assumption.

I'm trying to filter document based on items present in document rows.

If

class DocumentRows(models.Model):
    document = models.ForeignKey(Document, related_name="rows")
    ...

then you should be able to use

documents = Document.objects.filter(rows__item=item_id).distinct()
Вернуться на верх