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!
You can try like this:
Details.objects.filter(ref_det__user_id__in=['2231', '973','431'])
You can try like this:
list(filter(lambda x: x.ref_det.get('user_id') in ['2231', '973','431'], Details.objects.all())) # it will return a list not queryset
FYI: I tried this with Django 1.10.8
, but I think, you can do lookup operations like contains
, in
, isnull
inside JSONField(reference).