在模板中显示多对多字段

时间:2016-04-22 07:21:26

标签: django

我遇到这种情况:

型号: -

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)

1 个答案:

答案 0 :(得分:0)

你的过滤器完全没有意义。要为发布者迭代作者,您可以{% for author in obj.author_set.all %}(假设obj是Publisher对象,您尚未显示)。

这里似乎与多对多关系没有任何关系。