Django:1.10
In conclusion, it was listed below.
QuerySet API reference | Django documentation | Django https://docs.djangoproject.com/ja/1.10/ref/models/querysets/#in
For queries, you should look at this page.
For example, to generate a query to get a list of books published by the selected author, write:
views.py
def search(request):
form = SearchForm(request.POST)
books = None
if form.is_valid():
books = Book.objects.filter(author_id__in = form.cleaned_data['author'])
return render(request, 'books/search.html', {'form': form, 'books': books})
Author, book, genre model.
models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Genre(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=512)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
genres = models.ManyToManyField(Genre)
def __str__(self):
return self.name
A form to select an author.
forms.py
from django import forms
from books.models import Author
class SearchForm(forms.Form):
authors = [(author.id, author.name) for author in Author.objects.all()]
author = forms.MultipleChoiceField(label='Author', widget=forms.CheckboxSelectMultiple,
choices=authors, required=False)
If the template is as follows,
searth.html
<form method="post" action="">
{% csrf_token %}
<h1>{{ form.author.label }}</h1>
{{ form.author }}
<input type="submit" value="Search" />
<hr />
<table border="1">
<tr>
<th>title</th>
<th>Author</th>
<th>Genre</th>
</tr>
{% for b in books %}
<tr>
<td>{{ b.name }}</td>
<td>{{ b.author.name }}</td>
<td>{% for g in b.genres.all %}{{ g.name }}{% endfor %}</td>
</tr>
{% endfor %}
</table>
</form>
It will be displayed like this.
I was implementing the addition of authors, but one problem came up. I get authors from the table to select authors in the above forms.py, but this method seems to be application scope, and even if I add authors, it will not be reflected on the screen unless the server is restarted. I will consider separately what to do when assigning transaction data to choices.
The above problem has been solved.
Choices not updated in Django's Multiple Choice Field http://qiita.com/nakkun/items/26598a7bf1f80b215ff2
Maybe this should be fine. .. ..
Recommended Posts