3
class Library(models.model):
    book = JSONField(default=[], blank=True, null=True)

possible structure of 'book' is {'title':'' ,'no_of_pages': '', 'author_name': '', 'color': '', edition: ''}

I am trying to write a django query that returns only records where book has at least one key with non empty value ( i.e either title or no_of_pages or author_name or color or edition has some value)

one possible solution to this is something like:

Author.objects.filter(
    ~Q(book__title='') |
    ~Q(book__no_of_pages='') | 
    ~Q(book__author_name='') |
    ~Q(book__color='') |
    ~Q(book__edition='')
)

is there any better way to do this ? There may be case where book can have some additional keys in future like publisher or availabilty

How can I perform this filter without having to mention the specific keys of the field ( just check at least one key with some value) ? or any shorter method to write this query with all the keys mentioned ?

priyankarani
  • 91
  • 1
  • 2
  • 5

2 Answers2

0
Author.objects.filter(book__has_any_keys=['title', 'no_of_pages', 'author_name', 'color'])

try this as specified in documentation, if this works for you.

Sumeet Kumar
  • 969
  • 1
  • 11
  • 22
  • above solution checks only keys in the table but does not ensure their values. I want to check if atleast one value is specified for any key. for e.g If have two rows 1. {{'title': 'Example' ,'no_of_pages': '', 'author_name': '', 'color': '', edition: ''} 2. {'title':'' ,'no_of_pages': '', 'author_name': '', 'color': '', edition: ''} Filter should return only first one as title has some value. – priyankarani May 21 '18 at 05:24
0

The list of authors where the book is not the empty dict.

Author.objects.filter(~Q(book__exact={}))
cdosborn
  • 3,111
  • 29
  • 30