Cześć
Mam prosty projekt w Pythonie i FastApi. Do tego używam bazy MySQL. Mam tabele produkt i producent, chciałabym mieć dwie dodatkowe kolumny 'product_code', która zawiera ciąg 'PC-{id}', gdzie {id} oznacza id danego produktu, oraz 'manufacturer_code', która ma postać {short_code}-{number}, gdzie number to liczba porządkowa produktu danego producenta.
Moje tabele:
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True, index=True)
manufacturer_id = Column(Integer, ForeignKey("manufacturers.id"), nullable=False)
name = Column(String, index=True, unique=True)
description = Column(String)
is_available = Column(Boolean, nullable=False, default=True)
price = Column(Integer, nullable=False)
manufacturer = relationship("Manufacturer", back_populates="products")
class Manufacturer(Base):
__tablename__ = "manufacturers"
id = Column(Integer, primary_key=True, index=True)
company_name = Column(String, index=True, unique=True)
short_code = Column(String, index=True, unique=True)
country = Column(String)
description = Column(String)
products = relationship("Product", back_populates="manufacturer")
Dla przykładu, dla producenta o polu short_code równym 'AVM', która ma 3 produkty, te produkty będą miały manufacturer_code, kolejno: 'AVM-1', 'AVM-2', 'AVM-3'.
Produkt o id=33, będzie miał product_code wynoszący 'PC-33'.
Niestety, nie wiem jak to zrobić. To znaczy wiem, ale tak "ręcznie" - dla 'product_code': pobierać produkty i wyznaczać ostatnie id, dodawać jeden i wstawiać przy zapisie do bazy danych. Dla 'manufacturer' - pobierać listę produktów dla danego producenta i zliczać je, a potem dodawać plus jeden i tworzyć string przy zapisie.
Ale czy nie ma jakieś lepszej metody na to? Np. w definicjach tabel dodawać jakieś pola/ustawienia aby te sekwencje tworzyły się automatycznie?