1

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?

1 Answer 1

1

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")
]
Sign up to request clarification or add additional context in comments.

3 Comments

I got error response of AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'>
Sorry, I forgot to return in get function of OrderView class. I changed the code. So please check it out.
How would you change this if let's say every order can have multiple products and you want to return only the 2 most expensive products with each order? How not to create n+1 queries to lookup for the 2 products for each order?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.