python - 获取所有对象 ID 的列表

标签 python django python-3.x django-1.10

我有 model Product 作为主键使用代码字段,它是 UUID。我想获取所有产品的 ID 列表。

我想要这样的列表:

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

我尝试了下一个代码,但它返回给我:

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

模型.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)

如何解决这个问题?

最佳答案

您可以使用 .values_list()在你的 Queryset 上设置 flat=True对象以展平模型的 codestr 列表与 map将每个 UUID 对象类型化为字符串:

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

另请参阅 UUID examples uuid 的典型用法模块。

关于python - 获取所有对象 ID 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889428/

相关文章:

python - 谷歌或工具: Employee Scheduling with availability constraint

python - 线性回归器无法预测一组值;错误 : ValueError: shapes (100, 1) 和 (2,1) 未对齐 : 1 (dim 1) ! = 2(暗淡 0)

javascript - 如何将 Angular 2 应用程序集成到 Django 应用程序中

python - 在 HTML 文件中导入 Python 代码

Python:在匹配行之后从文件中提取3行

python - wand - 文本换行 - 基于图像文件大小

python - 尝试从 s3 获取图像并打开图像时出现 OSError : cannot identify image file <_io. BytesIO 对象位于 0x00000198001B9E08>

python - 将 LinkedIn API 时间转换为 Python 中的标准日期

python - Django:从 getter 方法返回的 models.CharField() 值为空

python - Django Rest Framework : CreateAPIView, 存储数据时我想使用主键