Queryset model Category, Product and Productimage

Asked

Viewed 104 times

0

Hello, help me assemble 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 this: In my "site" the customer chooses the category. There is listed all products in the category. Up to this point I managed to return the products with the name, price, etc. The doubt is: how will I search for the image of this product?

See 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

summarized the code, but who wants to see the complete project access https://github.com/leonardocintra/cleonice

Grateful!

  • take a look at this github...you’ll find what you need. https://github.com/codingforentrepreneurs/ecommerce-2

1 answer

1

First upgrade your Productimage model 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 attribute related_name, if you do not use the attribute it is possible to do so:

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

More details on documentation

  • Hugo, thank you. A doubt: How will I go through the image in my template?

  • I did so: Return Product.objects.prefetch_related('images'). filter(category__slug=self.kwargs['Slug'])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.