S
S
Sama Samsonov2016-12-27 14:17:23
Django
Sama Samsonov, 2016-12-27 14:17:23

How to filter by foreignkey?

There is a model
class Author(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
class Book(models.Model):
title = models.CharField(max_length=100)
language = models.CharField(max_length=2, choices=(('RU', 'Russian'), ('EN', 'English')))
author = models.ForeignKey(Author)
publisher = models.ManyToManyField(Publisher)
publication_date = models.DateField()
Authorlinked by ForeignKey
There are 3 authors and 9 books linked by 3rd author in the database
How do I sort by author ? Which author has how many books?
if 'publ' in request.GET and request.
publ = request.GET['publ']
publi = Book.objects.filter(author=publ)
publ when from template via selectbox
publi = Book.objects.filter(author=publ) Not working how to make filter ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2016-12-27
@samuser

publi = Book.objects.filter(author_id = publ)
And the design

if 'publ' in request.GET and request.GET['publ']:
publ = request.GET['publ']

#красивее заменить на
publ = request.GET.get('publ', None)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question