CartSerializer Documentation
This section outlines the serializer used in the Cart API. The CartSerializer is responsible for transforming the data between complex types (e.g., Django models) and Python data types (e.g., JSON), allowing the creation, update, and retrieval of shopping cart information.
Serializers
- Cart Serializer:
CartSerializer
1. Cart Serializer
Serializer Overview
CartSerializer is used to serialize shopping cart data. A shopping cart contains multiple cart items, user information, and calculates important fields such as subtotal, total discount, final total, and the total number of items in the cart.
Fields
| Field | Type | Description |
|---|---|---|
id |
integer |
The unique identifier for the cart. |
user_id |
integer |
The ID of the user associated with the cart. |
items |
array |
A list of cart items serialized using CartItemSerializer. |
subtotal |
decimal |
The subtotal of the cart before discounts. |
total_discount |
decimal |
The total discount applied to the cart. |
final_total |
decimal |
The final total after applying the discount. |
total_items |
integer |
The total number of items in the cart. |
created_at |
datetime |
The timestamp when the cart was created. |
updated_at |
datetime |
The timestamp when the cart was last updated. |
Example Response
Response
{
"id": 1,
"user_id": 123,
"items": [
{
"id": 1,
"product": {
"id": 101,
"name": "Product Name",
"price": 50.00,
"discount_percent": 10,
"description": "A detailed description of the product.",
"images": [
{
"id": 1,
"image": "http://example.com/media/products/product1_image.jpg"
}
],
"primary_image": "http://example.com/media/products/product1_image.jpg"
},
"variant": {
"id": 201,
"variant_price": 45.00,
"discounted_price": 40.50,
"stock_quantity": 10,
"is_available": true,
"is_active": true,
"size": {
"id": 301,
"size": "L",
"value": "Large"
}
},
"quantity": 2,
"total_price": 90.00,
"discount_amount": 9.00,
"final_price": 81.00,
"is_direct_purchase": false,
"has_purchased": false,
"created_at": "2024-12-06T14:30:00Z",
"updated_at": "2024-12-06T14:30:00Z"
}
],
"subtotal": 90.00,
"total_discount": 9.00,
"final_total": 81.00,
"total_items": 1,
"created_at": "2024-12-06T14:30:00Z",
"updated_at": "2024-12-06T14:30:00Z"
}
Serializer Methods
CartSerializer.get_total_items(self, obj)
This method returns the total number of items in the cart by counting the related cart_items.
CartSerializer.get_subtotal(self, obj)
This method calculates the subtotal of the cart by summing the total_price of each cart_item.
CartSerializer.get_total_discount(self, obj)
This method calculates the total discount applied across all cart items by summing the discount_amount of each cart_item.
CartSerializer.get_final_total(self, obj)
This method calculates the final total by subtracting the total discount from the subtotal, ensuring the result is never negative. It returns the final value rounded to two decimal places.