Search code examples
django-modelsdjango-rest-frameworkdjango-serializer

How to include related models using Django Rest Framework ListAPIView


Having 2 models and i need a list, a single queryset of lists that will combine all related fields from the 2 models.

class Product(models.Model):
     name = models.CharField(...)
     price= models.Decimal(...)
     image = models.ImageField(...)
     description2 = models.TextField(....)

class Order(models.Model):
     buyer = models.CharField(...)
     product = models.ForeignKey(Product, on_delete=models.CASCADE)

have it return something that includes the full related model. A queryset Lists of ORDER with this result

   {
    "id": 1,
    "buyer": 1,       
    "product": 3,
    "name": "Product 1",
    "image": "url",
    "price": 10.50
  },
  {
    "id": 2,
    "buyer": 2,       
    "product": 2,
    "name": "Product 2",
    "image": "url",
    "price": 6.50
  },

OR

{
    "id": 1,
    "buyer": 1,       
    "product": [
    {
       'id': 1,
       'name': 'Product 1',
       'image': "url",
       'price': 10.50
    }], 
  },
  {
    "id": 2,
    "buyer": 2,       
    "product": [
    {
       'id': 2,
       'name': 'Product 2',
       'image': "url",
       'price': 6.50
    }], 
}

Is this possible?


Solution

  • First, you need to define the serializer in serializers.py file.

    from rest_framework import serializers
    from .models import Product, Order
    
    class ProductSerializer(serializers.ModelSerializer):
        class Meta:
            fields = "__all__"
            model = Product
    
    class OrderSerializer(serializers.ModelSerializer):
        product = ProductSerializer(read_only = True)
        
        class Meta:
            fields = ("buyer", "product", )
            model = Order
    

    And then, you need to create the ListAPIView for Order in views.py file.

    from rest_framework import generics, mixins
    from .models import Order
    from .serializers import OrderSerializer
    
    class OrderView(mixins.ListModelMixin, generics.GenericAPIView):
        queryset = Order.objects.all()
        serializer_class = OrderSerializer
    
        def get(self, request, *args, **kwargs):
             return self.list(request, *args, **kwargs)
    

    Last you need to add the api url in urls.py,

    from .views import *
    urlpatterns = [
        path('orders', OrderView.as_view(), name="order")
    ]