[Answered ]-Applying class method to queryset in Django

2👍

From official documentation:

from django.db import models

class Reporter(models.Model):
    # ...
    pass

class Article(models.Model):
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

In the above example, the methods below will be available on the manager reporter.article_set.

Also, you can use prefetch_related method which will join your data in one query.

In your case code should look like:

order_list = Order.objects.filter(...).prefetch_related('vendor_agreement')
for order in order_list:
    print order
    for vendor_agreement in order.vendor_agreement_set.all():
        print vendor_agreement

Code from my example will hit database only once.

Leave a comment