List of all values in Django model attribute

29 Views Asked by At

I am creating an e-commerce website and I want to allow the user to filter the search results by various products specs.

I want to return in my API a meta dictionary containing all the values each product attribute has.

For example, if the user searches for 'iPhone', the response should look like this:

{
    'data': {
        ...
    },
    'meta':{
        'options':{
            'model': ['iPhone 12', 'iPhone 13', 'iPhone 14'],
            'manufacturer': ['Apple'],
            ...
        }
    }
}

Here is my model for reference:

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, null=False, blank=False)
    description = models.TextField(max_length=2048, null=False, blank=True)
    price = models.FloatField(null=False, blank=False, default=0)
    model = models.CharField(max_length=255, null=False)
    manufacturer = models.CharField(max_length=255, null=False)
    seller = models.CharField(max_length=255, null=False)

So far i have tried using this, where products is my QuerySet of Product entities after applying the 'iPhone' search:

products.values_list('model')

The problem with this is that it returns a QuerySet, but I want a list.

I was hoping there is a one-liner that I don't know about.

1

There are 1 best solutions below

0
Marco On

Convert it to a list. You can also use flat=True when querying only one attribute (check the docs):

list(products.values_list('model', flat=True))