Answer the question
In order to leave comments, you need to log in
How to implement such an if, for construct in an html file?
There are two models Book and Author (the codes will be below). You need to write this: if the Author has a Book, then each Book will be displayed in the list. There is a Many-to-One relationship between Book and Author:
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True)
def display_genre(self):
return ', '.join([genre.name for genre in self.genre.all()[:3]])
display_genre.short_description = 'Genre'
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('book-detail', args=[str(self.id)])
class Author(models.Model):
"""
Model representing an author.
"""
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('Died', null=True, blank=True)
def get_absolute_url(self):
"""
Returns the url to access a particular author instance.
"""
return reverse('author-detail', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return '%s, %s' % (self.last_name, self.first_name)
Answer the question
In order to leave comments, you need to log in
models.py:
class Book(models.Model):
...
author = models.ForeignKey(Author, related_name="books", on_delete=models.SET_NULL, null=True)
...
def index(request):
context = {}
authors = Author.objects.all()
context['authors'] = authors
return render(request, 'index.html', context)
...
<div>
{% for author in authors %}
<h1>{{ author.first_name }}</h1>
{% for book in author.books.all %}
<h4>{{ book.title }}</h4>
{% empty %}
<p>Похоже, у этого автора нет книг :(</p>
{% endfor %}
{% endfor %}
</div>
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question