O
O
Ozrae2020-03-09 18:41:13
Django
Ozrae, 2020-03-09 18:41:13

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

1 answer(s)
W
Wondermarin, 2020-03-09
@Ozrae

models.py:

class Book(models.Model):
    ...
    author = models.ForeignKey(Author, related_name="books", on_delete=models.SET_NULL, null=True)
    ...

views.py:
def index(request):
    context = {}
    authors = Author.objects.all()
    context['authors'] = authors
    return render(request, 'index.html', context)

index.html:
...
    <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>
...

And the author model must be declared before the book model.
I also advise you to read this: https://docs.djangoproject.com/en/3.0/topics/db/qu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question