Skip to main content

Overview

The tables module manages restaurant tables, customer orders, order items, and invoice generation.

Mesa

Restaurant table model with state management.
id
AutoField
required
Primary key for the table. Auto-generated by Django.
nombre
CharField
required
Table name or identifier.
  • max_length: 50
descripcion
TextField
Table description or notes.
  • blank: True
estado
CharField
Current state of the table.
  • max_length: 20
  • choices: ESTADO_CHOICES
  • default: ‘disponible’

Estado Choices

ESTADO_CHOICES
list
Available table states:
ValueDisplay
disponibleDisponible
ocupadaOcupada
reservadaReservada
fuera de servicioFuera de servicio
  • pedidos: Reverse relation to Pedido (related_name=‘pedidos’)

Pedido

Customer order model tracking items ordered at a table.
id
AutoField
required
Primary key for the order. Auto-generated by Django.
mesa
ForeignKey
Reference to the table where the order was placed.
  • to: Mesa
  • on_delete: SET_NULL
  • related_name: ‘pedidos’
  • null: True
  • blank: True
usuarios
ManyToManyField
Users associated with this order.
  • to: User (Django auth)
  • related_name: ‘pedidos_asociados’
  • blank: True
fecha_creacion
DateTimeField
Timestamp when the order was created.
  • auto_now_add: True
fecha_actualizacion
DateTimeField
Timestamp of last update.
  • auto_now: True
estado
CharField
Current state of the order.
  • max_length: 20
  • choices: ESTADO_CHOICES
  • default: ‘en_proceso’

Estado Choices

ESTADO_CHOICES
list
Available order states:
ValueDisplay
en_procesoEn Proceso
facturadoFacturado
canceladoCancelado

Methods

  • items: Reverse relation to PedidoItem (related_name=‘items’)
  • factura: Reverse OneToOne relation to Factura (related_name=‘factura’)

PedidoItem

Individual item within an order.
id
AutoField
required
Primary key for the order item. Auto-generated by Django.
pedido
ForeignKey
required
Reference to the parent order.
  • to: Pedido
  • on_delete: CASCADE
  • related_name: ‘items’
producto
ForeignKey
required
Reference to the product being ordered.
  • to: Producto (from products app)
  • on_delete: PROTECT
cantidad
PositiveIntegerField
Quantity of the product ordered.
  • default: 1
  • Must be a positive integer
precio_unitario
DecimalField
Unit price at the time of order.
  • max_digits: 10
  • decimal_places: 2
  • default: 0

Methods

The precio_unitario stores the price at the time of order, preserving historical pricing even if the product’s current price changes.

Factura

Invoice model for completed orders.
id
AutoField
required
Primary key for the invoice. Auto-generated by Django.
pedido
OneToOneField
required
Reference to the order being invoiced.
  • to: Pedido
  • on_delete: PROTECT
  • related_name: ‘factura’
  • Each order can have only one invoice
numero
CharField
required
Invoice number.
  • max_length: 20
  • unique: True
  • Auto-generated with 8-digit zero-padded format
fecha
DateTimeField
Invoice date and time.
  • default: timezone.now
total
DecimalField
Total invoice amount.
  • max_digits: 10
  • decimal_places: 2
  • default: 0
  • Auto-calculated from order total if not provided

Methods

Invoice numbers are sequential and formatted as 8-digit strings (e.g., “00000001”, “00000002”).

Usage Examples

Creating a Table

from tables.models import Mesa

mesa = Mesa.objects.create(
    nombre="Mesa 1",
    descripcion="Mesa cerca de la ventana",
    estado="disponible"
)

Creating an Order

from tables.models import Pedido, PedidoItem, Mesa
from products.models import Producto
from django.contrib.auth.models import User

# Get table and user
mesa = Mesa.objects.get(nombre="Mesa 1")
user = User.objects.get(username="mesero1")

# Create order
pedido = Pedido.objects.create(
    mesa=mesa,
    estado="en_proceso"
)
pedido.usuarios.add(user)

# Add items to order
producto1 = Producto.objects.get(nombre="Coca-Cola 350ml")
producto2 = Producto.objects.get(nombre="Hamburguesa")

PedidoItem.objects.create(
    pedido=pedido,
    producto=producto1,
    cantidad=2,
    precio_unitario=producto1.precio_venta
)

PedidoItem.objects.create(
    pedido=pedido,
    producto=producto2,
    cantidad=1,
    precio_unitario=producto2.precio_venta
)

# Get order total
total = pedido.total()

Generating an Invoice

from tables.models import Factura

# Create invoice for order
factura = Factura.objects.create(
    pedido=pedido
)
# numero and total are auto-generated

# Update order status
pedido.estado = "facturado"
pedido.save()

# Update table status
mesa.estado = "disponible"
mesa.save()

Querying Orders

# Get all orders for a table
orden_mesa = Mesa.objects.get(nombre="Mesa 1")
pedidos = orden_mesa.pedidos.all()

# Get active orders
pedidos_activos = Pedido.objects.filter(estado="en_proceso")

# Get orders by user
user_orders = user.pedidos_asociados.all()

# Get order items with product details
for item in pedido.items.select_related('producto'):
    print(f"{item.cantidad}x {item.producto.nombre} - ${item.subtotal()}")

Invoice Queries

from django.utils import timezone
from datetime import timedelta

# Get today's invoices
hoy = timezone.now().date()
facturas_hoy = Factura.objects.filter(fecha__date=hoy)

# Get invoices for date range
fecha_inicio = timezone.now() - timedelta(days=7)
facturas_semana = Factura.objects.filter(fecha__gte=fecha_inicio)

# Get invoice with order details
factura = Factura.objects.select_related('pedido__mesa').get(numero="00000001")
print(f"Factura: {factura.numero}")
print(f"Mesa: {factura.pedido.mesa.nombre}")
print(f"Total: ${factura.total}")

Build docs developers (and LLMs) love