I have my models:
class Volume(models.Model):
volnumber = models.IntegerField('Volume Number', primary_key=True)
year = models.TextField()
#...#
class Article(models.Model):
volnumber = models.ForeignKey(Volume)
title = models.TextField(blank=True)
开发者_JS百科 slug = models.SlugField(max_length=100, db_index=True)
#...#
my view:
# Article detail
def article_detail(request, slug):
return render_to_response('article_detail.html', {
'article': get_object_or_404(Article, slug=slug),
})
my template:
{{ article.volume.year }}. <strong class="title">{{ article.title }}</strong>.Journal Vol.{{ article.volnumber }}
The problem is I am not getting any output for the year (title and volnumber are fine). The syntax seems correct..what am I doing wrong?
Try:
{{ article.volnumber.year }}
Since you're simply following the relationship forward, article.volnumber
should give you a reference to the associated Volume object.
You're not seeing anything in your template because article
does not have a volume
attribute. The templating engine fails silently and nothing is printed.
Better yet, to make the references more intuitive you might want to consider renaming the attribute in your Article
model from volnumber
to simply volume
.
class Article(models.Model):
volume = models.ForeignKey(Volume)
# ...
Using article.volume.year
and article.volume.volnumber
is, in my opinion, a lot more readable than article.volnumber.volnumber
.
精彩评论