在Django中在模板中显示数据的最佳方法是什么?

时间:2012-05-17 13:54:13

标签: django templates model

鉴于以下模型和观点,对于任何给定的俱乐部,我试图在模板中显示该俱乐部的可用法院(“法院”)和可用时间(“avail_time”)。我无法做到这一点。

型号:

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 %}

2 个答案:

答案 0 :(得分:1)

嗯,你似乎没有Court模型,所以我不确定你为什么要打电话给court_set.all。您可以使用club.available_set.all来显示该俱乐部的可用实例列表,这可能就是您的意思。

答案 1 :(得分:0)

第一步是适当地设置模型。俱乐部有法院和法院有时间。俱乐部没有“可用时间”,这就是您现在设置的方式。此外,“take”是可用时间的状态;它不应该是一个模型本身。尝试类似:

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 %}