2017-04-10 95 views
0

在我的代碼我創建這個 '字典' 類型的數組:Django的查詢JSON結果

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

請在實際在'result'中進行查詢的循環之前顯示位。正如錯誤所述,您不知何故獲取了字典,而不是UsageStatistics實例,但沒有看到代碼,我們無法幫助您。 –

+0

@DanielRoseman完成。 –

回答

2

你可以做

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

這工作,謝謝 –

1

如果你只想要值,你可以做一個列表c omprehension ...

in_array = [X [ 'content_reference'] [ '參考']在結果X]

比你有值的列表中選擇您in_array: [ '160',' 159','162']