2

所以我有这些模型:

Bands(models.Model):
    mgmt = models.ForeignKey(User)
    name = models.Charfield(max_length=200)

Contracts(models.Model):
    band = models.ForeignKey(Bands)
    start_date= models.DateField()

BookedGig(models.Model):
    for  = models.ForeignKey(Bands)
    under= models.ForeignKey(Contracts)
    date = models.DateField()

我将如何在我的 views.py 文件中构造一些东西来为用户捕获所有 BookedGigs?我的目标只是通过模板显示联系人/乐队标题下的各种演出。

在 views.py 我目前有

def Home(request):
    user = request.user
    bands = Bands.objects.filter(mgmt=user).order_by('name') 
        #This will give me the bands belonging to a user
    contracts = Contracts.filter(band=bands)
        #But here bands is not one value but a queryset.

    #if I try
    contracts = bands.booked_gig_set.all() 
    I get 'QuerySet' object has no attribute 'booked_gig_set'

模板:我知道这是错误的,但这就是我想要显示列表的方式。

{% for b in bands %}
    Band:{{b.name}}
    {% for c in contracts %}
        Contract Start:{{c.start_date}}
        {% for g in gigs %}
            {{g.dates}}
        {% endfor %}
    {% endfor %}
{% endfor %}

谢谢

4

1 回答 1

4
 Contracts.objects.filter(band__in=bands)

不过,您可能希望在此处添加一条prefetch_related语句来预取演出,否则您的模板循环将在每个合同中访问数据库一次。

 contracts = Contracts.objects.filter(band__in=bands).prefetch_related()
于 2013-09-03T21:03:27.873 回答