在我的代码中,我创建了这个'dict'类型数组:
blog_reference = {'reference': kwargs.get('reference')}
它保存在数据库表格列 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'
我写过这个数据库查询:
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]
它给出了结果:
<QuerySet [
{'total': 1, 'content_reference': {'reference': '160'}},
{'total': 1, 'content_reference': {'reference': '159'}},
{'total': 1, 'content_reference': {'reference': '162'}}
]>
使用此 FOR 循环,我尝试访问content_reference ['参考']的所有值(即160,159,162)并将它们放入数组中的 in_array
for item in result:
content_reference = json.loads(item['content_reference'])
in_array.append(content_reference.reference)
这是错误 content_reference = json.loads(item.content_reference)正在创建的完整回溯:
回溯:
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'
答案 0 :(得分:2)
你可以做到
for item in result:
content_reference = item['content_reference']
in_array.append(content_reference['reference'])
答案 1 :(得分:1)
如果您只想要这些值,您可以进行列表理解......
in_array = [x [&#39; content_reference&#39;] [&#39;参考&#39;] for x in result]
你的in_array将包含值列表: [&#39; 160&#39;,&#39; 159&#39;,&#39; 162&#39;]