0

So I've got this model with this JSONField -

class Details(models.Model):
    ref_det = JSONField(null=True, default=dict())

ref_det stores values in this format

{'user_id': '2231', 'org_id': 'qpdkm12'}

Each object of the model has its ref_det as a dictionary of just those two values.

Now I have this list of user IDs - user_ids - and I want to get those objects from the model where the user_id key in its ref_det field contains any of those user_id in the user_ids list.

So if I have user_ids = ['2231', '973','431'], I should get those Details objects whose ref_det has its user_id as any of the 3 values in the list.

I tried looking up through contains, but I think that supports lookups of only a single value and not a list.

I think __values__contains (https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fields/#hstorefield) is appropriate for this usecase, but then again, I don't have an HStoreField.

Does anyone know how I can get through this?

Thanks!

4

1 回答 1

2

Django 1.10 或更高版本:

你可以这样尝试:

 Details.objects.filter(ref_det__user_id__in=['2231', '973','431'])

Django 1.9:

你可以这样尝试:

 list(filter(lambda x: x.ref_det.get('user_id') in ['2231', '973','431'], Details.objects.all()))  # it will return a list not queryset

仅供参考:我尝试使用Django 1.10.8,但我认为,您可以在 JSONField( reference ) 中执行诸如containsin、之类的查找操作。isnull

于 2018-10-30T08:44:54.323 回答