class Parent(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Child(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey("Parent", on_delete=models.CASCADE, related_name="child")
def __str__(self):
return self.name
Parent (1) : Child (N) 의 관계
class ParentSerializer(serializers.ModelSerializer):
child = ChildSerializer(many=True)
class Meta:
model = user_models.Parent
fields = ("name", "child",)
class ChildSerializer(serializers.ModelSerializer):
class Meta:
model = post_models.Child
fields = ("name",)
class ParentView(APIView):
def get(self, request):
parent = Parent.objects.prefetch_related("child")
serializer = ParentSerializer(parent, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)