1

I have model Product where as primary key use code field which is UUID. I want take list of ids of all products.

I want list like this:

['14431ec4-3224-480f-85e2-b541891919b1', '6e54636b-7283-4504-a16f-f54d29db26f2']

I tried next code but it return me this:

[UUID('14431ec4-3224-480f-85e2-b541891919b1'), UUID('6e54636b-7283-4504-a16f-f54d29db26f2')]

models.py:

class Product(models.Model):
    code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)

views.py:

products = Product.objects.all()
product_ids = []
for product in products:
    product_ids.append(product.code)
print(product_ids)

How to fix this problem?

Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

3 Answers3

3

You may use .values_list() with flat=True on your Queryset object to flatten the list of model's code and str with map to type-case each UUID object to string as:

map(str, Product.objects.all().values_list('code', flat=True))

Please also see UUID examples for the typical usage of the uuid module.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

This is just because it is a UUID field. If you definitely need them as strings, just call str():

product_ids = [str(product.code) for product in products]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

You can get string value using .hex from uuid as follows:

 ids = [product.uuid.hex for product in products]
Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36