Home > front end >  Django - how to get data from relationships?
Django - how to get data from relationships?

Time:06-16

I try to get data over a many-to-many and a one-to-many relationship.

view.py

class PublisherDetailView(generic.DetailView):
     model = Publisher
     template_name = 'store/publisher_detail_view.html'

models.py

class Publisher(models.Model):
    name = models.CharField(null=False, max_length=30)
    image = models.ImageField(upload_to='publisher_images/')
    
class Book(models.Model):
    title = models.CharField(null=False, max_length=30)
    description = models.CharField(max_length=1000)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
    
class reader(models.Model):
    name = models.CharField(max_length=40)
    book = models.ManyToManyField(Book)

publisher_detail_view.html

{% for reader in publisher.book_set.readers.all %}
    <p>{{ reader.name }} </p>
{% endfor %}

I just want to get all readers from a specfic publisher. What is the right code in the template? publisher.book_set.readers.all makes sense to me (early beginner), but doesn't work

CodePudding user response:

book_set.readers doesn't work because book_set is a manager that manages a list of books. To get the readers, you have to iterate through the books:

{% for book in publisher.book_set.all %}
    {% for reader in book.reader_set.all %}
        <p>{{ reader.name }} </p>
    {% endfor %}
{% endfor %}
  • Related