Home > Enterprise >  find unique values in django
find unique values in django

Time:07-30

I am a beginner with Django. My question is, How can i retrieve all unique category name in search_result?

My models.py

class Category(models.Model):
    category_name = models.CharField(max_length=20, unique=True)
    logo = models.ImageField(upload_to='Category')
    slug = models.SlugField(unique="True")
 
    def __str__(self):
        return self.category_name



class Product(models.Model):
    product_name = models.CharField(max_length=50, blank=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", blank=True, related_name="Products")
    price = models.FloatField(blank=False, default=0.00, validators=[MinValueValidator(0.0)], help_text='Price Can not be Less than Zero.')
 
    def __str__(self):
        return self.product_name

My views.py

class SearchView(TemplateView):
    template_name = "productstemplate/products.html"
 
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user_search = self.request.GET['product']
        search_result = Product.objects.filter(Q(product_name__icontains=user_search) |
             Q(category__category_name__icontains=user_search))
 
        context['products'] = search_result

        context['categorys'] =  ===>>  Here <<===

        return context

CodePudding user response:

You can create a list that contains all category_name values and then map it to set and then again to list.

category_name_list = [e.category__category_name for e in search_result]
context['categorys'] = list(set(category_name_list))

A different approach can be writing new query with distinct() method:

context['categorys'] = Product.objects.filter(Q(product_name__icontains=user_search) |
         Q(category__category_name__icontains=user_search)).values_list('category__category_name', flat=True).distinct()

CodePudding user response:

Why not create a list that contains category_name values ​​and then list it again? Our friend who left this comment I also agree and I think your problem will be completely solved try again!

  • Related