-2
領域我有這種情況:顯示許多一對多模板
型號: -
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
date = models.DateTimeField()
class Meta:
ordering = ["-name"]
def __unicode__(self): # __unicode__ on Python 2
return self.name
class Author(models.Model):
publisher = models.ForeignKey(Publisher)
salutation = models.CharField(max_length=10)
name = models.CharField(max_length=200)
email = models.EmailField()
headshot = models.ImageField(upload_to='author_headshots')
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField('Author')
publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
publication_date = models.DateField()
def __str__(self):
return self.title
def get_authors(self):
return "\n".join([a.name for a in self.authors.all()])
我要顯示在模板作者場出版商
模板:
{% for a in obj.pk|get_author %}
{{ a.name }}<br/>
{{ a.headshot }}
{% endfor %}
定製模板標籤:
def get_author(pk):
try:
publisher = Publisher.objects.get(pk=pk)
print type(publisher)
author = Author.objects.filter(Publisher=publisher)
print author
except:
author = []
return author
register.filter('get_author', get_author)
什麼不工作? – Sayse