How does Django's manager objects work, when accessing them through reverse relationships ?

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"]]

Cart is a Model

Cart.objects is a Manager

cart = Cart.objects.get(id=1)

cart is an instance of a Cart

cart.items is a RelatedManager which can return the items related to the cart.

If you haven’t done so already, go through and play around with the examples in the Django tutorial and then the Django rest framework tutorial. From that, you should start to understand how relations work in the ORM, and then how Django rest framework magic can turn orm models into rest api endpoints.

1 Like

This is not an accurate statement.

There’s nothing “special” or particularly important about the name “objects”. It’s the default name used by Django for a manager for accessing a model.

You can create as many managers as you want.

You can even create a default manager with a different name.

See the docs at Managers | Django documentation | Django

1 Like

I see, thanks

BTW if my question is answered is there any way to mark this draft as solved or something like that, so other people know that they can find a solution here ?

Underneath the answer you wish to choose as the solution, click on the “checkbox” icon. (It should show up as about the 4th icon to the left of the “Reply” icon. If it’s not there yet, it will show up in a bit.)