2012-05-17 40 views
0

鑑於以下模型和觀點,對於任何給定的俱樂部,我都試圖在模板中展示該俱樂部的可用法院(「法庭」)和可用時間(「avail_time」)。這樣做有困難。在Django的模板中顯示數據的最佳方式是什麼?

型號:

from django.db import models 

class Club(models.Model): 
    establishment = models.CharField(max_length=200) 
    address = models.CharField(max_length=200) 
    def __unicode__(self): 
    return self.establishment 

class Available(models.Model): 
    club = models.ForeignKey(Club) 
    court = models.CharField(max_length=200) 
    avail_time = models.DateTimeField('available time') 
    def __unicode__(self): 
     return self.court 

class Taken(models.Model): 
    club = models.ForeignKey(Club) 
    court = models.ForeignKey(Available) 
    taken_time = models.DateTimeField('taken time') 
    userid = models.EmailField(max_length = 75) 

查看:

def avail_times(request, club_id): 
    p = get_object_or_404(Club,pk=club_id) 
    return render_to_response('reserve/templates/avail_times.html', {'club':p}) 

模板:

{% for court in club.court_set.all %} 
{{court.court }} 
{% endfor %} 

回答

1

嗯,你似乎並不有一個法院的模式,所以我不知道爲什麼你要撥打court_set.all。您可以使用club.available_set.all來顯示該俱樂部的可用實例列表,這可能就是您的意思。

0

第一步將適當地設置您的模型。俱樂部有法院和法院有可用的時間。俱樂部沒有可用的時間,這是你現在設置的方式。此外,「採取」是可用時間的狀態;它本身不應該是一個模型。嘗試是這樣的:

class Club(models.Model): 
    establishment = models.CharField(max_length=200) 
    address = models.CharField(max_length=200) 

    def __unicode__(self): 
     return self.establishment 

class Court(models.Model): 
    club = models.ForeignKey(Club, related_name='courts') 
    name = models.CharField(max_length=200) 

class CourtTime(models.Model): 
    AVAILABLE = 0 
    TAKEN = 1 
    STATUS_CHOICES = (
     (AVAILABLE, 'Available'), 
     (TAKEN, 'Taken'), 
    ) 

    court = models.ForeignKey(Club, related_name='times') 
    time = models.DateTimeField('available time') 
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=STATUS_CHOICES[AVAILABLE]) 

    def __unicode__(self): 
     return self.court 

然後,我會建議一個自定義的經理在CourtTime返回可用/取查詢集:

class CourtTimeQuerySet(models.query.QuerySet): 
    def available(self): 
     return self.filter(status=CourtTime.STATUS_CHOICES[CourtTime.AVAILABLE]) 

    def taken(self): 
     return self.filter(status=CourtTime.STATUS_CHOICES[CourtTime.TAKEN]) 

class CourtTimeManager(models.Manager): 
    use_for_related_fields = True 

    def get_query_set(self, *args, **kwargs): 
     return CourtTimeQuerySet(self.model) 

    def available(self, *args, **kwargs): 
     return self.get_query_set().available(*args, **kwargs) 

    def taken(self, *args, **kwargs): 
     return self.get_query_set().taken(*args, **kwargs) 

然後,將其添加到您的模型:

class CourtTime(models.Model): 
    ... 
    objects = CourtTimeManager() 

隨着所有這些,您可以在您的模板中執行以下操作:

{% for court in club.courts.all %} 
    <h2>{{ court.name }}</h2> 
    <ul> 
     {% for time in court.times.available %} 
     <li>{{ time|date:"m/d/Y g:i A" }}</li> 
     {% endfor %} 
    </ul> 
{% endfor %} 
相關問題