Home > Software design >  How to apply filtering over order by and distict in django orm?
How to apply filtering over order by and distict in django orm?

Time:11-30

Name            email                 date
_________________________________________________

Dane            [email protected]        2017-06-20
Kim             [email protected]         2017-06-10
Hong            [email protected]        2016-06-25
Dane            [email protected]        2017-06-04
Susan           [email protected]       2017-05-21
Dane            [email protected]        2017-02-01
Susan           [email protected]         2017-05-20

I can get the first entries of each unique by using EmailModel.objects.all().order_by('date').distinct('Name'). this returns

 Name            email                 date
_________________________________________________

Dane            [email protected]        2017-06-20
Kim             [email protected]         2017-06-10
Hong            [email protected]        2016-06-25
Susan           [email protected]       2017-05-21

What i want to do here is to only include it in the result if the very first entry is something different like more filtering over it? for ex- i don't want to include it in the result if the first email id is [email protected] for Dave and only include it if it is something different.

CodePudding user response:

You can use F() expressions with __istartswith lookup to exclude those emails which starts with their name so:

EmailModel.objects.exclude(email__istartswith=F('Name')).order_by("date").distinct("Name")

Or you'd like to avoid the Name in entire email so you can use __icontains lookup so:

EmailModel.objects.exclude(email__icontains=F('Name')).order_by("date").distinct("Name")

CodePudding user response:

Supposed your model name is User So for order by with filter you can used

User.object.filter(parameters).order_by(parameters)

  • Related