所以我有这些模型:
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 %}
由于
答案 0 :(得分:3)
Contracts.objects.filter(band__in=bands)
你可能想在那里添加一个prefetch_related
statement来预取演出,否则你的模板循环会在每个合约中命中一次。
contracts = Contracts.objects.filter(band__in=bands).prefetch_related()