我有下面的查询,我想获取'specs'这是一个字典,但envi_dict的类型是一个Queryset类。如何从此查询集中获取字典?任何帮助深表感谢。
envi_dict = Environment.objects.values('specs')
结果
<QuerySet [({u'CPU Model': u'Dell', u'RAM': 1000, u'CPU': 400},), ({u'CPU Model': u'Dell', u'RAM': 1000, u'CPU': 400},)]>, <class 'django.db.models.query.QuerySet'>, )
我尝试了Environment.objects.filter(title=item.title).values('specs')
和Environment.objects.get('specs')
,但我仍然获得了一个查询集。
修改:以下是models.py
class CommonModel(models.Model):
author = models.ForeignKey('auth.User',)
title = models.CharField(max_length=400)
comments = models.TextField(blank=True)
requirements = JSONField(default = {})
specs = JSONField(default= {})
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(blank=True, null=True)
class Meta:
abstract = True
def update(self):
self.updated_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Estimate(CommonModel):
gp_code = models.TextField(default='Unknown')
inputs = models.TextField(blank=True)
...
def __str__(self):
return self.title
class Environment(CommonModel):
estimate = models.ForeignKey(Estimate,related_name='environments')
logic = PythonCodeField(blank=True, null=True)
...
答案 0 :(得分:2)
使用模型instance.title作为键构建dicts列表,并通过迭代所有Environment模型实例将specs作为值。
[{i.title: i.specs} for i in Environment.objects.all()]
答案 1 :(得分:0)
single queryset
转换为字典,请使用
model_to_dict
。all querysets
转换为字典,请使用Model.objects.values()
或django.core.serializer 使用model_to_dict
from django.forms.models import model_to_dict
qs = Environment.objects.filter(title=item.title)
if qs is not None:
qs_dict = model_to_dict(qs) # {id:1,'estimate':'some-estimate-data','logic':'some-logic-data'}
# Do something here with qs_dict
else:
# qs=None -- do some here when qs is not found