0

鉴于以下模型和视图,对于任何给定的俱乐部,我试图在模板中显示该俱乐部的可用球场(“球场”)和可用时间(“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 %}
4

2 回答 2

1

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

于 2012-05-17T14:02:26.217 回答
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 %}
于 2012-05-17T14:52:08.400 回答