QuerySet model Category, Product and ProductImage

0

Hello, help me build this queryset.

Briefly, the model model.py

class Category(models.Model):
    name = models.CharField('Nome', max_length=100)
    slug = models.SlugField(max_length=100, unique=True)
    created = models.DateField('Criado em', auto_now_add=True)
    modified = models.DateField('Modificado em', auto_now=True)

class Product(models.Model):
    name = models.CharField('Nome', max_length=100)
    slug = models.SlugField('Identificador', max_length=100, unique=True)
    category = models.ForeignKey('catalog.Category', verbose_name='Categoria')
    description = models.TextField('Descrição', blank=True)
    price = models.DecimalField('Preço', decimal_places=2, max_digits=8)

class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = CloudinaryField('Imagem', blank=True, null=True)
    description = models.CharField('Descrição', max_length=200, blank=True, default='')

What I want to do is the following: In my "site" the customer chooses the category. Here you can find all the products in this category. Until that point I was able to return the products with the name, price, etc. The doubt is: How will I get the image of this product?

Look at the view.py

from django.views import generic

class CategoryListView(generic.ListView):
    """
    Lista os produtos de determinada categoria (Bolo ou Biscoitos)
    """
    template_name = 'catalog/category.html'
    context_object_name = 'product_list'
    paginate_by = 10

    def get_queryset(self):
       return Product.objects.filter(category__slug=self.kwargs['slug'])

    def get_context_data(self, **kwargs):
        context = super(CategoryListView, self).get_context_data(**kwargs)
        context['current_category'] = get_object_or_404(Category, slug=self.kwargs['slug'])
        # tenho a categoria
        # pela categoria consigo achar os produtos
        # achando os produto consigo achar as imagens
        # e ai como que faz ?
        return context

I have summarized the code, but anyone who wants to see the complete project accesses link

Thank you!

    
asked by anonymous 08.02.2017 / 00:09

1 answer

1

First update your Model ProductImage with related_name :

class ProductImage(models.Model):
     product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
     image = CloudinaryField('Imagem', blank=True, null=True)
     description = models.CharField('Descrição', max_length=200, blank=True, default='')

So it is possible to do a query like this:

 product = Product.objects.get(category=category)
 images = product.images.all()

This is possible due to the related_name attribute, if you do not use the attribute you can do this:

 product = Product.objects.get(category=category)
 images = product.productimagem_set.all()

More details on the documentation

    
08.02.2017 / 03:49