Home > Blockchain >  How to order by queryset by Saturday to Sunday in django?
How to order by queryset by Saturday to Sunday in django?

Time:09-12

I want to order an attendance queryset by Saturday to Friday. How can I achieve it?

class ReportsTogether(models.Model):
    user = models.ForeignKey(User,on_delete=CASCADE,verbose_name=_("Report For User"))
    user_log = models.ManyToManyField(UserTimeInOut,verbose_name=_("User Attendance"))
    user_break = models.ManyToManyField(UserBreak,verbose_name=_("User Break"))
    user_lunch = models.ManyToManyField(UserLunchBreak,verbose_name=_("User Lunch 
    Break"))

    time = models.DateField(verbose_name=_("Date"),null=True)

CodePudding user response:

You can use order_by and week_Day combination on queryset to order it by weekday.

Something like this:

qs=Modelname.objects.all().order_by('-time__week_day')

This will order result by weekdays in desc order from sat to sunday as day 1 being Sunday and day 7 being Saturday.

CodePudding user response:

This should do what you want:

from django.db.models import F
qs = ReportsTogether.objects.annotate(my_week_day=F('time__week_day')%7).order_by('my_week_day')

According to the doc: "Takes an integer value representing the day of week from 1 (Sunday) to 7 (Saturday).", you just need to get the weekday value and take its modulo of 7

  • Related