Friday, June 26, 2020

Re: Django queryset filtering

I'd make two queries. One to see which businesses currently have active licenses, then a second to get the expired licenses, excluding the businesses from the first query. Here's some example code, assuming the LicenseIssue model has a "business" foreign key field:

active_business_ids = LicenseIssue.objects.filter(expiry_date__gt=TODAY).values_list('business_id', flat=True).distinct()
expired_licenses = LicenseIssue.objects.filter(expiry_date__lte=TODAY).exclude(business_id__in=active_business_ids).order_by('-expiry_date')

On Wednesday, June 24, 2020 at 6:25:18 PM UTC-4 mtp...@gmail.com wrote:
I have a queryset that returns all the expired licenses objects as shown below.

qs = LicenseIssue.objects.filter(expiry_date__lte=TODAY).order_by('-expiry_date')    

Here is my situation:
There exists multiple issued licenses of different businesses for year 2020 and their  previous issued licenses for the for year 2019, 2018 and so on. The above queryset results to listing all expired licenses though I'd like to make it possible if there exists issued licenses for year 2020 their previous issued licenses should not appear in the expired licenses queryset. Please advise on this.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9a0c6125-efc6-4127-98cc-30ffadd01195n%40googlegroups.com.

No comments:

Post a Comment