Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django prefetch_related failing to pass data to template

I have two Django models:

class Product(models.Model):
    name = models.CharField(max_length=80, null=True)
    is_active = models.BooleanField(default=False, null=False)

class Image(models.Model):
    url = models.CharField(max_length=255, unique=True, null=False)
    product = models.ForeignKey('Product', related_name='images')

I have a specific set of products. Each product has multiple images. The initial call looks something like:

product_list = product_list.filter(is_active=True).prefetch_related('images')

The product_list then gets whittled down depending on filters that are applied.

When I try to use the product_list within the display layer (template), I iterate the list of products. I can access all the product's fields except its images.

{{ product.images.0.id }} ==> empty

{{ product.images }} ==> returns Image.None

Running the code through the debugger, I can see the Image SQL query being executed, it's just that none of the data is passed to the template. There definitely is data there, as I can verify the query running it through my SQL client. Does any one know why this is happening? How do I get access to the Images for a given product?

like image 687
Huckleberry Stenstrom Avatar asked Jan 16 '16 20:01

Huckleberry Stenstrom


1 Answers

I solved my issue. The prefetched data had to accessed like: product.images.all.0.id

like image 148
Huckleberry Stenstrom Avatar answered Oct 08 '22 21:10

Huckleberry Stenstrom