Converts the model object to JSON!
Well then This time when getting the Book object Get the Author referenced by ForeignKey including the object !!!!!!!!!!!!
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)
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__'
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__'
In the output result, the data omitted in the sample model is also output !! Please skip it !!

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!
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__'
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__'

That's it!
Recommended Posts