I thought you can only access the manager object of a model only through .objects. Then how in the below code we are able to access the manager object of cart items model through the reverse relationship in cart model without calling “.objects” in the line “cart.items.all()” ?
It would be helpful to get some insights on how manager objects work ?
serializers.py
class CartSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True)
items = CartItemSerializer(many=True, read_only=True)
total_price = serializers.SerializerMethodField(
method_name="get_total_price")
def get_total_price(self, cart: Cart):
return sum([item.quantity * item.product.unit_price for item in cart.items.all()])
class Meta:
model = Cart
fields = ["id", "items", "total_price"]
For reference models.py
class Cart(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4)
created_at = models.DateTimeField(auto_now_add=True)class CartItem(models.Model):
quantity = models.PositiveSmallIntegerField()cart = models.ForeignKey( Cart, on_delete=models.CASCADE, related_name="items") product = models.ForeignKey(Product, on_delete=models.CASCADE) class Meta: unique_together = [["cart", "product"]]