简体   繁体   中英

Django Query Json Result

In my code I create this 'dict' type array:

blog_reference = {'reference': kwargs.get('reference')}

It is saved into the database table column content_reference :

class UsageStatistics(models.Model):
    content_type_choices = (
        ('unspecified', 'Unspecified'),
        ('blog', 'Blog'),
        ('newsletter', 'Newsletter'),
        ('video', 'Video'),
    )
    reference = models.BigAutoField(primary_key=True)
    access_date = models.DateTimeField(blank=True, null=True)
    ip_address = models.GenericIPAddressField()
    passport_user = models.ForeignKey('Passport', models.DO_NOTHING, blank=True, null=True)
    language_iso = models.TextField()
    content_type = models.CharField(
        max_length=12,
        choices=content_type_choices,
        default='unspecified'
    )
    content_reference = JSONField()

    class Meta:
        db_table = 'usage_statistics'

I've wrote this database query:

result = UsageStatistics.objects.filter(
    content_type='blog',access_date__gte=datetime.utcnow() - timedelta(days=90)
).values('content_reference').annotate(
    total=Count('reference')
).order_by('-total')[:10]

It gives the result:

<QuerySet [
    {'total': 1, 'content_reference': {'reference': '160'}}, 
    {'total': 1, 'content_reference': {'reference': '159'}}, 
    {'total': 1, 'content_reference': {'reference': '162'}}
]>

With this FOR loop I am trying to access all the values of content_reference[' reference '] (namely 160 , 159 , 162) and put them into the array in_array .

for item in result:
    content_reference = json.loads(item['content_reference'])
    in_array.append(content_reference.reference)

This is the full traceback for the error content_reference = json.loads(item.content_reference) is creating:

Traceback:

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/rpiggott/PyCharmProjects/rons-home.net/blog/views.py" in popular
  253.     result = ServicePopular.search()

File "/home/rpiggott/PyCharmProjects/rons-home.net/blog/service/popular.py" in search
  34.             b = json.loads(item.content_reference)

Exception Type: AttributeError at /en/blog/popular
Exception Value: 'dict' object has no attribute 'content_reference'

You can do

for item in result:
    content_reference = item['content_reference']
    in_array.append(content_reference['reference'])

If you want only the values, you can do a list comprehension ...

in_array = [x['content_reference']['reference'] for x in result]

Than you will have your in_array with the list of values : ['160', '159', '162']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM