Ilya Bibik
Ilya Bibik

Reputation: 4124

Can I use Prefetch_related to prefetch more than just one model?

In my view I a prefetching related data in order to read it later from the template

soproduct = SOproduct.objects.select_related('product__material').prefetch_related(
        Prefetch(
            'product__material__bomversion_set',
            queryset=BOMVersion.objects.default().active(),
            to_attr='default_active_bomversions'
        )
    )

I have never user prefetch before and got it from one of the answers on stackoverflow.

However is it possible to prefetch more than one table ?

I have another table content of which I also want to display in the same template So near each combination of soproduct and BOM I want to display relevant values from Production_order

    @with_author  
class Production_order(models.Model):
    version = IntegerVersionField( )
    creation_time = models.DateTimeField(auto_now_add=True, blank=True)
    BOM = models.ForeignKey(BOM, on_delete=models.PROTECT)
    soproduct = models.ForeignKey(SOproduct, on_delete=models.PROTECT)
    agent = models.ForeignKey(User, on_delete=models.PROTECT)
    quantity_order = models.DecimalField(max_digits=19, decimal_places=3)
    is_active = models.BooleanField(default=True)
    is_production= models.BooleanField(default=False)
    is_prepared = models.BooleanField(default=False)
    is_picked = models.BooleanField(default=False)
    production_notes = models.TextField(null=True, blank=True)
    inventory_notes = models.TextField(null=True, blank=True)

Upvotes: 0

Views: 65

Answers (1)

wobbily_col
wobbily_col

Reputation: 11921

Yes, just add comments between the entries.

I have never used the Prefetch object before, Just use prefetch_related as follows:

soproduct = SOproduct.objects.select_related('product__material').prefetch_related(
                 'product__material__bomversion_set',
                 'second_table',
                 'third_table__fourth_table'
                  )

Upvotes: 1

Related Questions