[PYTHON] Get a reference model using Django Serializer

To put it simply, Serializer!

Converts the model object to JSON!

Well then This time when getting the Book object Get the Author referenced by ForeignKey including the object !!!!!!!!!!!!

define model

This is a sample model! The Book model refers to the ʻAuthor` model!

models.py


class AbstractModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    is_deleted = models.CharField(max_length=1, default='0')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Author(AbstractModel):
    first_name = models.CharField(max_length=128)
    last_name = models.CharField(max_length=128)

class Book(AbstractModel):
    title = models.CharField(max_length=128)]
    sub_title = models.CharField(max_length=128)]
    price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
    author = models.ForeignKey(Author, on_delete=models.PROTECT, blank=True, null=True)

Get the referrer model as well

Define View

Create a get API using the generics ListAPIView! ʻAuthormodel is also acquired, so queryset Specify author inselect_related. It is possible to get it because it is ʻall (), but select_related. ('author') By specifying in advance, you can reduce the amount of SQL to be issued !!

views.py


from django_filters import rest_framework as filters
from rest_framework import generics

from book.models import Book, Author
from book.serializers import BookSerializer

class ListBook(generics.ListAPIView):
    """API to get a list of Books"""
    queryset = Book.objects.select_related('author')
    serializer_class = BookSerializer
    filter_backends = [filters.DjangoFilterBackend]
    filterset_fields = '__all__'

Define the referrer Serializer in Serializer

You can define a destination Serializer in the BookSerializer field! Now you can also get the related model !!!

However, one thing to note here is the serializer that is the reference source. Don't get me wrong as the field name is related to lookup when defining Please !!

serializer.py


class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = '__all__'


class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()
    class Meta:
        model = Book
        fields = '__all__'

The result is here !!!!

In the output result, the data omitted in the sample model is also output !! Please skip it !!

スクリーンショット 2020-10-22 3.59.33.png

Get the referenced model

Earlier, I also got the Book model and the ʻAuthormodel of the reference source, On the contrary, I would like to getBook from ʻAuthor !!. the method is easy!

Define View

I would like to get it using ListAPIView. This time, there is no problem with ʻall ()as it is withoutselect_related`.

views.py


class ListAuthor(generics.ListAPIView):
    """Get Author"""
    queryset = Author.objects.all()
    serializer_class = AuthorBookSerializer
    filter_backends = [filters.DjangoFilterBackend]
    filterset_fields = '__all__'

Serializer definition

It is book_set to get the referenced model! Now when you request the API, you can get the Author and Book. At this time, if you leave ʻauthor = AuthorSerializer ()inBookSerializer Note that when you get thebook, you will get the ʻauthor again.

serializers.py


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'


class AuthorBookSerializer(serializers.ModelSerializer):
    book_set = BookSerializer(many=True)
    class Meta:
        model = Author
        fields = '__all__'

The result is here !!!!

スクリーンショット 2020-10-22 3.51.45.png

That's it!

Recommended Posts

Get a reference model using Django Serializer
Creating a learning model using MNIST
WEB application development using Django [Model definition]
Implement a Custom User Model in Django
Django model: ManyToManyField
If you want to display values using choices in a template in a Django model
Creating an interactive application using a topic model
Run a Python file from html using Django
[Python] Implementation of clustering using a mixed Gaussian model
Build a Django development environment using pyenv-virtualenv on Mac
How to get multiple model objects randomly in Django
Get the file name in a folder using glob
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Building a seq2seq model using keras's Functional API Overview
I tried hosting a Pytorch sample model using TorchServe
DJango Note: From the beginning (using a generic view)
Build a Python virtual environment using venv (Django + MySQL ①)
Make the model a string on a Django HTML template
Machine Learning with Caffe -1-Category images using reference model
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
Building a seq2seq model using keras' Functional API Inference
How to reference static files in a Django project
PyTorch Learning Note 2 (I tried using a pre-trained model)
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
[Django] Give Form a dynamic initial value from Model
Create a Django schedule
[Day 9] Creating a model
Model changes in Django
High Performance Django --Model
Start a Django project
Implementation of VGG16 using Keras created without using a trained model
Create a shogi game record management app using Django 4 ~ Create View ~
[Django] Manage settings like writing in settings.py with a model
Build a seq2seq model using keras's Functional API Model building & learning
The story of a Django model field disappearing from a class
I tried hosting a TensorFlow deep learning model using TensorFlow Serving
How to generate a query using the IN operator in Django
[Django] Create a model suitable for phone numbers / zip codes
I made a VGG16 model using TensorFlow (on the way)
Try to model a multimodal distribution using the EM algorithm
Create an easy-to-use follow model in Django using ManyToManyField through
[Django Learned with the Devil's Blade] How to get a query set for forward / reverse reference