4

I have below query where I want to fetch 'specs' which is a dictionary but the type of envi_dict is a Queryset class. How do I fetch the dictionary from this queryset? Any help is much appreciated.

envi_dict = Environment.objects.values('specs')

Result

<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'>, )

I tried Environment.objects.filter(title=item.title).values('specs') and also Environment.objects.get('specs') but I am still getting a queryset.

Edit: Below is 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)
    ...
Heenashree Khandelwal
  • 659
  • 1
  • 13
  • 30

2 Answers2

10

Build a list of dicts with model instance.title as key and the specs as value by iterating over all Environment model instances.

[{i.title: i.specs} for i in Environment.objects.all()]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 3
    if you want one dict object then it will be: `{i.title: i.specs for i in Environment.objects.all()}` without adding the comma. – elsadek Dec 28 '21 at 16:15
1

Use Django model_to_dict

  • If you need to convert a single queryset into a dictionary, use model_to_dict.
  • If you need to convert all querysets into a dictionary use Model.objects.values() or django.core.serializer

using model_to_dict

from django.forms.models import model_to_dict
 
qs = Environment.objects.filter(title=item.title)
 
if qs.exists():
  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
 
CbeDroid1614
  • 51
  • 1
  • 3