Custom handler or through model

Tl dr: should I use an intermediate model “through” or a custom handler for adding a quantity to a many to many field

Context: I’m building a cashier system as a learning project. An order can contain different quantities of dishes. An order could have two club sandwiches for instance.

Google gemini suggested a through model coupling the sandwich to a quantity and adding this to the order.
An alternative is to use a custom manager and add methods for adding sandwiches.

The through model seems to generate overhead as this creates a dB table.

What is custom practice?
Advice here?

By definition, a many-to-many relationship is created within a relational database as a join-table (what Django refers to as the “through” table) between the two related tables. This is exactly how such things are modeled.

So you’d recommend the through model instead of a custom handler?

These are two separate topics.

A Model, whether it’s a regular model or a through model, is a reference to a table in a database.

A Manager is code that operates on a Model. You don’t store data in a Manager.

Exactly.

But both can be used to accomplish the goal outline by my initial post.
My question is what is common practice in my case?

I can hardly imagine my sandwich shop is rare example. As such, my question is, what would a seasoned Django developer recommend.

It’s not an either / or situation. An actual solution for what you’re trying to do is likely going to involve both together.

OK, thanks. Your insights are helpful.

This is what gemini proposed.
This or a through model with a quantity field.
I suppose that would be easier to couple to a form later on now that I think of it.

What do you think?

from django.db import models

class Order(models.Model):
# … other order fields

sandwiches = models.ManyToManyField("Sandwich", related_name="orders")

objects = OrderManager()  # Use custom manager

class OrderManager(models.Manager):

def add_sandwich(self, order, sandwich, quantity):
    # Logic to add sandwich to order with specified quantity
    pass

def remove_sandwich(self, order, sandwich):
    # Logic to remove sandwich from order
    pass

I think that code fragment doesn’t do anything. It’s meaningless.

You’ve got two separate and discrete issues to address.

  1. How you are going to store the data in the database.

  2. How you are going to add, update, remove that data from the database.

And, you should answer those two questions in that order.

Design your data first. Make sure you understand what you’re storing, and why.

Only after that, can you reliably work on the code that processes that data.