n00b question about displaying data in order by day

22 views
Skip to first unread message

Becka R.

unread,
Nov 7, 2015, 12:03:25 AM11/7/15
to Django users
Hi --

I'm building a scheduling app for my burning man camp.  There are seven days (Mon-Sun), and each day has two meals, and people can sign up for the available shifts. 

Here's my table:

class mealShifts(models.Model):
Sunday = "Sunday"
Monday = "Monday"
Tuesday = "Tuesday"
Wednesday = "Wednesday"
Thursday = "Thursday"
Friday = "Friday"
Days = (
(Sunday, "Sunday"),
(Monday, "Monday"),
(Tuesday, "Tuesday"),
(Wednesday, "Wednesday"),
(Thursday, "Thursday"),
(Friday, "Friday"),
)
Breakfast = "Breakfast"
Dinner = "Dinner"
Meals = (
(Breakfast, "Breakfast"),
(Dinner, "Dinner"),
)
Chef = "Chef"
Sous_Chef = "Sous-Chef"
KP ="KP"
Shifts = (
(Chef, "Chef"),
(Sous_Chef, "Sous_Chef"),
(KP, "KP"),
)
assigned = models.BooleanField(default=False)
day = models.CharField(max_length = 10, choices=Days, default=Sunday)
meal = models.CharField(max_length = 10, choices=Meals, default=Dinner)
shift = models.CharField(max_length = 10, choices=Shifts, default=KP)
camper = models.OneToOneField(User)

class Meta:
unique_together = ("day", "meal", "shift")

def __str__(self):
return '%s %s %s %s'%(self.day, self.meal, self.shift, self.camper)


And my views function:

def signup(request):
shifts = mealShifts.objects.all()
username = None
if not request.user.is_authenticated():
return 
if request.method == 'POST':
form = MealForm(request.POST)
if form.is_valid():
shift = form.save(commit=False)
shift.camper = request.user
shift.save()
return redirect('signup')

else:
form = MealForm()
return render_to_response('signup.html', 
RequestContext(request, {'form':form,'shifts':shifts, 'username':username},))

 
And here's the part of the template that displays the shifts:

<h2>Shifts</h2>
<div id="datatable">
<ul>
{% for shift in shifts %}
<li>{{shift.camper}} {{shift.day}} {{ shift.meal }} </li>
{% endfor %}
</ul>
</div>
</div>


How can I display the data in the template so the shifts are sorted by day, and then by meal?

Thank you,

Becka

Florian Schweikert

unread,
Nov 7, 2015, 5:38:31 PM11/7/15
to django...@googlegroups.com
On 07/11/15 06:03, Becka R. wrote:
> How can I display the data in the template so the shifts are sorted by
> day, and then by meal?

Try saving the weekday as integer (0-6), sorting using integer is much
easier than sorting using strings in non-alphabetic order :)
You can than e.g. define a default ordering for your model:
https://docs.djangoproject.com/en/1.8/ref/models/options/#ordering
or sort it in the view:
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.order_by

--
Florian

signature.asc
Reply all
Reply to author
Forward
0 new messages