2016-04-22 88 views
-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) 
+0

什麼不工作? – Sayse

回答

0

您的過濾器完全沒有意義。爲了遍歷發佈者的作者,您可以執行{% for author in obj.author_set.all %}(假設obj是Publisher對象,您尚未顯示)。

儘管這裏似乎沒有任何與多對多關係有關的事情。