1

I am trying to get the book list with 3 conditions:

  1. Accession number (character varying,10)
  2. Physical location (character varying,20)
  3. Book status

Based on the user input:

  1. Accession number should be present in the list provided by the user
  2. Physical location should be exact match
  3. Book status should be 'Published'

 

qobjects = Q()
variable_column = "accession_number"
search_type = 'in'
filter_string = variable_column + '__' + search_type
#Passed accessionNumber as '123','234',456'
#Also tried 123,456,567
#Both did not work
search_string = '['+accessionNumber+']'
qcolumn = Q(**{filter_string: search_string})
qobjects.add(qcolumn, Q.AND)
print('print qobjects after adding accession numbers')
print(qobjects)
location_column="physical_location"
search_type='iexact'
filter_string = location_column + '__' + search_type
qcolumn_location = Q(**{filter_string: location})
print('print qobjects after adding location')
print(qobjects)
qobjects.add(qcolumn_location,Q.AND)
qcolumn_status = Q(**{'booK_status': 'PUBLISHED'})
qobjects.add(qcolumn_status, Q.AND)
print('print qobjects after adding status')
print(qobjects)
res_set = Book.objects.filter(qobjects).order_by(location_column). \
    values('id', 'title', 'cover_image_name','booK_status',
           'accession_number', 'total_image_count',)
print('print result set')
print(res_set)
2
  • what is accessonNumber, a string? Commented Apr 30 at 7:50
  • Yes, that's right. It is a string. Commented Apr 30 at 7:57

1 Answer 1

2

Filter with:

search_type = "in"
res_set = Book.objects.filter(
    Q(
        *[
            Q((f"{f}__{search_type}", v.split(",")))
            for f, v in (
                ("accession_number", accessionNumber),
                ("physical_location", location),
            )
        ]
    ),
    booK_status="PUBLISHED",
).order_by(location_column)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.