How to filter a query_set for unique Django values

0

I'm trying to get unique value results from a query_set in django. What I want is for you to return me as many unique classifications There is.

Example. In a Table I have different articles that are classified by type

ID     |    NOMBRE    |    CLASIFICACION
1           Escoba         Limpieza
2           Trapeador      Limpieza
3           Tornillo       Herramienta

I want you to return me 2 classifications Cleaning and Tool. he currently returns me the 3 classifications Cleaning, Cleaning and tool.

my view:

class ItemListView(ListView):
    model= Items

    def get_context_data(self,**kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['clasificacion'] = Items.objects.order_by('nombre').distinct('clasificacion')
        return context

My Models

from django.db import models

# Create your models here.
class Items(models.Model):
    nombre = models.CharField(max_length=250)
    descripcion = models.CharField(max_length=250)
    codigo_proveedor = models.CharField(max_length=250)
    clasificacion = models.CharField(max_length=250)
    c_minima = models.IntegerField()
    c_actual = models.IntegerField()
    proveedor = models.ForeignKey('Proveedores', 
                on_delete=models.CASCADE)
    active = models.BooleanField()

        def __str__(self):
            return self.nombre + '   -----   ' + 
                   self.clasificacion + '   -----    ' + 
                   str(self.c_actual)


class Proveedores(models.Model):
    nombre = models.CharField(max_length=250)
    telefono = models.CharField(max_length=250)
    direccion1 = models.CharField(max_length=250)
    direccion2 = models.CharField(max_length=250, null=True)
    active =  models.BooleanField()

    def __str__(self):
        return self.nombre

I would appreciate your help

    
asked by victorR 14.04.2018 в 19:43
source

1 answer

0

Use values

 contexto['clasificacion'] =  Items.objects.values('clasificacion').order_by('clasificacion').distinct()

The function 'distinct ()' does not accept values, so first there is the 'values ()' with the parameters that we want to group. Once the desired values are obtained, they must be sorted by grouping them according to the list of values

I recommend that for cases like these, where a field will always have the same 4 or 5 values, use choices in the model, it will facilitate the development.

    
answered by 15.04.2018 / 00:03
source