How to generate a query using the IN operator in Django

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.

無題.png


Postscript 2016/11/26

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.

Postscript 2017/01/05

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

How to generate a query using the IN operator in Django
How to create a Rest Api in Django
How to generate a new loggroup in CloudWatch using python within Lambda
How to write a GUI using the maya command
How to execute a command using subprocess in Python
How to reference static files in a Django project
How to count the number of elements in Django and output to a template
How to write custom validations in the Django REST Framework
How to use Laravel-like ORM / query builder Orator in Django
How to use the __call__ method in a Python class
I made a command to generate a table comment in Django
How to unit test a function containing the current time using freezegun in python
How to reflect CSS in Django
How to get the last (last) value in a list in Python
In Django, how to abbreviate the long displayed string as ....
Get the query string (query string) in Django
How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
[sh] How to store the command execution result in a variable
How to determine the existence of a selenium element in Python
How to get all the possible values in a regular expression
How to check the memory size of a variable in Python
How to get the vertex coordinates of a feature in ArcPy
How to deploy a Django app on heroku in just 5 minutes
How to check the version of Django
How to draw a graph using Matplotlib
How to delete expired sessions in Django
How to install a package using a repository
How to get a stacktrace in python
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
[Django Learned with the Devil's Blade] How to get a query set for forward / reverse reference
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
How to make a model for object detection using YOLO in 3 hours
How to specify a .ui file in the dialog / widget GUI in PySide
How to get a value from a parameter store in lambda (using python)
Added a function to register desired shifts in the Django shift table
How to get a namespaced view name from a URL (path_info) in Django
How to fix the initial population with a genetic algorithm using DEAP
How to build an application from the cloud using the Django web framework
How to sort by specifying a column in the Python Numpy array.
How to calculate the volatility of a brand
How to use the C library in Python
How to code a drone using image recognition
How to clear tuples in a list (Python)
How to generate permutations in Python and C ++
How to implement Rails helper-like functionality in Django
How to embed a variable in a python string
How to create a JSON file in Python
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
How to generate a Python object from JSON
How to implement a gradient picker in Houdini
How to print debug messages to the Django console
How to notify a Discord channel in Python
How to get the files in the [Python] folder
[Python] How to draw a histogram in Matplotlib
Generate a hash value using the HMAC method.
How to write a named tuple document in 2020
How to count numbers in a specific range
How to upload to a shared drive using pydrive
How to copy and paste the contents of a sheet in Google Spreadsheet in JSON format (using Google Colab)