James
James

Reputation: 91

Python/Django - Querying Database

So I have a Django API server running on local host 127.0.0.1:8000.

This is the layout of my models.py:

models.py

class Book(models.Model):
    title = models.CharField(max_length=100)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __str__(self):
        return u'%s' % (self.title)

class Publisher(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    website= models.URLField()

    def __str__(self):
        return u'%s' % (self.name)

I run a query like the following in my views.py file:

book_list = Book.objects.all().values('title','publisher','publication_date')

When this query is run and handled, the value seems to return the Index of the Publisher in it's original table, as opposed to the name linked to it (for example, if it is the 3rd publisher in the Publisher table, then the value 3 will be returned for publisher).

Is there any way to get the actual name of the publisher that each value is linked to?

Many thanks!

Upvotes: 0

Views: 73

Answers (1)

Gabriel Samain
Gabriel Samain

Reputation: 507

Use fields lookup to access embedded object properties : https://docs.djangoproject.com/en/2.0/topics/db/queries/#field-lookups

Here use book_list = Book.objects.all().values('title','publisher__name','publication_date')

Upvotes: 5

Related Questions