Home > Net >  How to reverse filter based on latest entry in Django
How to reverse filter based on latest entry in Django

Time:11-30

I have a customer table and customer order table as below

class Customer(models.Model):
  name = models.CharField()

class CustomerOder(models.Model):
  customer = models.ForiengKey(Customer)
  item = models.CharField()
  datetime_of_purchase = models.DateField()

Sample database entry

Table: Customer

id    name
1     A
2     B
3     C

Table: CustomerOrder

id   customer   item     datetime_of_purchase
1    A          item_3   2021-11-10 10:00:00
2    A          item_2   2021-11-11 10:00:00
3    B          item_1   2021-11-11 10:00:00
4    A          item_1   2021-11-12 10:00:00
5    B          item_2   2021-11-12 10:00:00
6    C          item_1   2021-11-13 10:00:00

Suppose i need to filter customer whose latest purchase is 'items_1' so the sample after filtering should get only Customer 'A' and 'C' whose latest purchase is 'item_1'

Sample:
<QuerySet [<Customer: A>, <Customer: C>]>

CodePudding user response:

You can obtain the latest pruchased item with a Subquery expression [Django-doc]:

from django.db.models import OuterRef, Subquery

Customer.objects.alias(
    latest_purchase=Subquery(
        CustomerOrder.objects.filter(
            customer_id=OuterRef('pk')
        ).order_by('-datetime_of_purchase').values('item')[:1]
    )
).filter(latest_purchase='item_1')

Prior to , one uses .annotate(…) [Django-doc] over .alias(…) [Django-doc]:

from django.db.models import OuterRef, Subquery

Customer.objects.annotate(
    latest_purchase=Subquery(
        CustomerOrder.objects.filter(
            customer_id=OuterRef('pk')
        ).order_by('-datetime_of_purchase').values('item')[:1]
    )
).filter(latest_purchase='item_1')
  • Related