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.
UPDATE
class Document(models.Model):
...
class DocumentRows(models.Model):
document = models.ForeignKey(Document, related_name="rows")
item = models.ForeignKey(...)
Thanks
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.
UPDATE
class Document(models.Model):
...
class DocumentRows(models.Model):
document = models.ForeignKey(Document, related_name="rows")
item = models.ForeignKey(...)
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()
Document
as well or do you just want to fetch theDocument
matching those conditions? Perhaps you should explain exactly what data you want to fetch first instead of asking how to improve the query – Abdul Aziz Barkat Commented Feb 5 at 6:48