2017-04-11 92 views
1

我需要做同樣的事情:Django的JSONField和Q對象

# models.py 
from django.contrib.postgres.fields import JSONField, 

class MyModel(): 
    *** 
    ** 
    admin_fields = JSONField(_('admin fields'), blank=True, null=True, help_text=admin_fields_help_text) 


my_instances = MyModel.objects.filter((Q(my_model_id=pk) & 
     Q(children__isnull=True)) & 
     ~Q(admin_fields__status__contains='deleted')) 

或者

得到的所有記錄與id=pkchildren__isnull=True和JSONField admin_fields不得含有status==deleted

目前 admin_fields = {'status':'deleted'}

相反,它只返回r ecord有

admin_fields = {'status': 'deleted'} 

Is〜Q()不能與JSONField一起工作嗎?

想法?

感謝,

d

+0

你試過'MyModel.objects.filter((Q(my_model_id = PK) Q(children__isnull = TRUE)))。exlude(admin_fields__status__contains = '刪除')'?或者試試下面的MyModel.objects.filter(my_model_id = pk,children__isnull = True).exlude(admin_fields__status__contains ='deleted')' – Algorithmatic

+0

謝謝,我沒有想到絕對。它適用於一個小的變化:'MyModel.objects.filter(my_model_id = pk,children__isnull = True).exclude(admin_fields__contains = {'status':'deleted'})'。請添加它作爲答案。 – Daviddd

回答

1

你可以做你打算使用exclude()方法做什麼。

MyModel.objects.filter(my_model_id=pk, children__isnull=True).exclude(admin_fields__contains={'stat‌​us': 'deleted'})