我在 Django 应用程序中有两个数据表,一个包含船舶详细信息,另一个包含与单个船舶相关的报价。我的模型如下:
class Vessel(models.Model):
name = models.CharField(max_length=64)
image = models.CharField(max_length=64)
vesseltype = models.ForeignKey(VesselType)
capacity = models.IntegerField()
length = models.FloatField()
beam = models.FloatField()
speed = models.IntegerField()
activities = models.CharField(max_length=256)
category = models.IntegerField()
display_order = models.IntegerField()
published = models.BooleanField()
def __unicode__(self):
return self.name
class Offer(models.Model):
vessel = models.ForeignKey(Vessel)
description = models.CharField(max_length=128)
date = models.DateField()
duration = models.IntegerField()
itinerary = models.TextField()
price = models.IntegerField()
display_order = models.IntegerField()
link = models.URLField()
published = models.BooleanField()
def __unicode__(self):
return self.description
在我的views.py中,我有以下代码:
def home(request):
vessels = Vessel.objects.filter(published='y').order_by('display_order')
offers = Offer.objects.filter(vessel__published__exact='y').filter(published='y').order_by('display_order')
t = loader.get_template('index.html')
c = Context({
'vessels' : vessels,
'offers' : offers,
})
在模板中,我需要显示多个 div,每个 div 都包含船只名称、一些船只详细信息以及与该船只相关的任意数量的报价。
我查看了尝试将报价与每艘船只相关联的查询,并且我还尝试在模板中的循环代码中识别船只名称,以便仅在vessel.id 和offer.vessel 匹配时显示报价。
到目前为止,仅在查询端出现错误并通过模板方式单独列出船只名称和报价,都没有成功。如何加入这些信息,以便我可以在模板中使用类似这样的内容:
for offer in offers:
offer.vessel.name
offer.vessel.category
offer.description
offer.price
还是我期待太多?在这里待了几个小时,在文档中找不到解决方案,但这可能很明显。更改查询、视图代码或模板都不是问题。