Thursday, June 25, 2020

Re: Django queryset filtering

Hello, use a filtering chain, a refined queryset is itself a queryset so you can filter it further. Also, Django has extensive lookup support in its filtering methods. Let's assume LicenseIssue is related to Business as many to one (it is probably the case):

class Business(models.Model):
    name = models.CharField(max_length=15)

class LicenseIssue(models.Model):
    expiry_date = model.DateField(null=False)
    business = model.ForeignKey(Business, on_delete=models.CASCADE)

First you filter out expired licenses, second you exclude the licences which belong to businesses that have valid licences.

qs = LicenceIssue.objects.filter(expiry_date__lte=datetime.now()).exclude(business__license__expiry_date__gte='2020-01-01')

I have to point out that here license in business__license__expiry_date__gte is an automatically generated related_query_name.

Oleg

чт, 25 июн. 2020 г. в 01:25, mtp...@gmail.com <mtphlp@gmail.com>:
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/7d5ed088-c21b-4bd3-aba3-0f61c05efa50n%40googlegroups.com.

--
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/CAFAt%3DiwNZW_TM4J5oQ-5RjFb6fGok-n%2B1a2YjV_WgK7H8PX-ow%40mail.gmail.com.

No comments:

Post a Comment