I
I
Isaac Clark2012-09-09 17:04:59
Django
Isaac Clark, 2012-09-09 17:04:59

How to make a selection from a model with a ForeignKey?

Hello.
Tell me please.
There is this code:

#model
class Publisher(models.Model):
    name            =   models.CharField(max_length = 30)
    address         =   models.CharField(max_length = 30)
    city            =   models.CharField(max_length = 30)
    state_province  =   models.CharField(max_length = 30)
    country         =   models.CharField(max_length = 30)
    website         =   models.URLField()

    def __unicode__(self):
        return self.name

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


#views
def search(request):
    if 'q' in request.GET and request.GET['q']:
        q             =    request.GET['q']
        publishers    =    Publisher.objects.filter(name__icontains = q)

        return render_to_response('notices/search_result.html', {'publishers' : publishers, 'query' : q})

    else:
        return HttpResponse("Enter the search")


#base.html
<form action="/notice/search/" method="get">
    <select name="q">
        {% if publishers %}
            {% for publisher in publishers %}
                <option>{{ publisher.name }}</option>
            {% endfor %}
        {% endif %}
    </select>
</form>

This code finds and displays existing publishers from the database.
Question: please tell me how I need to change the code so that when choosing a publishing house and pressing the submit button, the list displays books that belong to this publishing house?
Thanks

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
vaxXxa, 2012-09-09
@vaxXxa

Offtopic: Read www.python.org/dev/peps/pep-0008/ and make the code pretty please. Then it is much easier to understand and read the code to others. Thank you.

A
alz, 2012-09-09
@alz

Make a form with a ModelChoiceField

A
admin4eg, 2012-09-10
@admin4eg

In the view something like this
'post_list':Post.objects.filter(category__uid=uid).order_by('-id')

F
FeNUMe, 2012-09-11
@FeNUMe

RTFM
selection of books by publisher name:

Book.objects.filter(publisher__name__exact=q)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question