0

Again I have same problem with query set

Following is the list for exclude some pattern in my query.

list = ['AW', 'cons', 'AR', 'AA', 'S1']

I am using the list contents one by one from the list and then using in below query set

objects_list = XeroLabourIndirect.objects.exclude(
            Q(job_num__istartswith='AW') |
            Q(job_num__istartswith='cons') |
            Q(job_num__istartswith='AR') |
            Q(job_num__istartswith='S1') |
            Q(job_num__istartswith='AA')) if obj else None

Instead of using the list content one by one in query set, I want to use my list inside query set with list comprehension method and iterate inside the query and then I have to get the resultant queryset.

For that what I have to do?

I tried something but all ends in syntax error, or some other errors. Please give some solution for my problem

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Sekar Raj
  • 113
  • 1
  • 1
  • 11
  • What version of Python are you using? – Kendas Jun 01 '17 at 07:11
  • 1
    `from functools import reduce` and `from operator import or_` and `XeroLabourIndirect.objects.exclude(reduce(or_, (Q(job_num__istartswith=w) for w in list)))`. – Martijn Pieters Jun 01 '17 at 07:19
  • Thanks @martijn pieters https://stackoverflow.com/questions/20222457/django-building-a-queryset-with-q-objects , this helped me for my solution. – Sekar Raj Jun 01 '17 at 07:24
  • why not using: XeroLabourIndirect.objects.filter(job_num__in = list). I don't test for using __istartswith_in so can't tell the result – Nam Nguyễn Jun 01 '17 at 07:27
  • @NamNguyễn: that's a very different test. That requires `job_num` values to be *equal* to any of those values. The test if they **start** with any of those values. – Martijn Pieters Jun 01 '17 at 07:33
  • Just explored here to see the answer. @MartijnPieters nice answer. :) – Aniket Pawar Jun 01 '17 at 07:41
  • that is why i wondering... can it work __istartswith and __in combo? I have to give it a try late on. Tell me if you got the result. Tks – Nam Nguyễn Jun 01 '17 at 08:20

0 Answers0