This is my Django models.py with 2 tables having a one-to-one table relationship. UserComputedInfo model has a one-to-one relationship with CustomUser model.
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth import get_user_model
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
post_code = models.DecimalField(max_digits=9, decimal_places=6)
def __str__(self):
return self.username
class UserComputedInfo(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
copy_input = models.DecimalField(max_digits=9, decimal_places=6)
def __str__(self):
return self.copy_input
I am trying to create a REST API to display all the fields in the 2 tables. I am using Django REST framework.
This is my serializers.py
from rest_framework import serializers
from users.models import CustomUser
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
fields = ("email", "post_code")
model = CustomUser
This is my views.py
from rest_framework import generics
from django.contrib.auth import get_user_model
from .serializers import CustomUserSerializer
class PostCodeAPIView(generics.ListAPIView):
queryset = get_user_model().objects.all()
serializer_class = CustomUserSerializer
The API will display all the fields in CustomUser table. However, I want to display all the fields in the related one-to-one UserComputedInfo table as well.
I am using Django v4, python v3.9, Django REST framework on Windows 10.