Skip to content Skip to sidebar Skip to footer

Display Model And Its Relations

My models.py is as follows: from django.db import models class Book(models.Model): book_id=models.AutoField(primary_key=True,unique=True) book_name=models.CharField(max_le

Solution 1:

Well, it doesn't look like you set up your models correctly first off. Django handles ids if none is provided so you don't need author_id=models.AutoField(primary_key=True). Also, shouldn't a book have an author, not an author have a book? If you do it correctly, you don't need author_name=models.CharField(max_length=30) either, cause you would have a foreign key to your Author model which has their name.

Once you set them up correctly, it is very easy to access the data in your template. For example, you would use book.author.first_name in your template to get the name of the book's author.


from django.db import models

classAuthor(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

    def__unicode__(self):
        returnu'%d %s %s' % (self.pk, self.first_name, self.last_name)

classBook(models.Model):
    name = models.CharField(max_length=30)
    author = models.ForeignKey(Author)
    publisher_name = models.CharField(max_length=40)

    def__unicode__(self):
        returnu"%d %s %s %s" % (self.pk, self.name, self.author.name, self.publisher_name)

template

{% for book in books %}
    ...
    {% for author in book.author_set %}
        ...
    {% endfor %}
{% endfor %}

Solution 2:

models.py

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    author_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        ..........

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    def __unicode__(self):
        ........

    def books(self):
        return Book.objects.filter(author=self)

views.py

defindex(request):
    authors = Author.objects.all()
    context={'authors':authors}
    return render(request,'index.html', context)

template

{% for author in authors %}
    Author: {{author.first_name}} {{author.last_name}}<br/>
    Email: {{author.email}}
    Age: {{author.age}}
    Books:
        {% for book in author.books %}
            .......
        {% endfor %}
{% endfor %}

Post a Comment for "Display Model And Its Relations"