django - improve the query structure or how can i use prefetch related - Stack Overflow

admin2025-04-16  7

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

Share Improve this question edited Feb 5 at 5:37 Ranu Vijay asked Feb 3 at 7:20 Ranu VijayRanu Vijay 1,29712 silver badges24 bronze badges 3
  • 1 Can you share the corresponding models and explain what you aim to retrieve? Not much how you want to retrieve it? – willeM_ Van Onsem Commented Feb 4 at 21:09
  • @willeM_VanOnsem I thought the question was self explanatory and not complicated. Updated the question for better understanding. – Ranu Vijay Commented Feb 5 at 5:48
  • Why would you want to use prefetch related for this? Do you want to fetch related models of Document as well or do you just want to fetch the Document 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
Add a comment  | 

1 Answer 1

Reset to default 1

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()
转载请注明原文地址:http://anycun.com/QandA/1744775867a87459.html