A
A
Alexander Lebedev2018-06-28 22:27:30
Python
Alexander Lebedev, 2018-06-28 22:27:30

How to add a column in SQLAlchemy that is based on another table column?

Good day.
There are three entities (SQLAlchemy tables, working with Flask SQLAlchemy):

  • Product (Samsung Galaxy 7)
  • Product variation (Samsung Galaxy 7 Coral Blue 32GB)
  • Order (includes product and variation)
Question: How can I make sure that in the orders table ( Order), the products column ( product_id) is not pulled through foreign_key, but is calculated by itself, based on the variation ( variation_id) added to the order? That is, we add Samsung Galaxy 7 Coral Blue 32GB to the order, and the product_idparent id of the product from the product table is automatically pulled into the column.
I tried using variation.parent_id, and backhref variation.origin_product, but without much success :)
Table models:
class Product(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), index=True)
    brand = db.Column(db.String(120))
    variations = db.relationship('Variation', backref='origin_product', lazy='dynamic')
    orders = db.relationship('Order', backref='product_in_order', lazy='dynamic')

class Variation(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), index=True)
    price = db.Column(db.Integer)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'))
    orders = db.relationship('Order', backref='variation_in_order', lazy='dynamic')

class Order(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    variation_id = db.Column(db.Integer, db.ForeignKey('variation.id'))
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'))

PS
product_id = db.Column(db.Integer, db.ForeignKey('variation.product_id'))
works in the database, I can see the correct product id. But tools like Flask-Admin still see it as the essence of a variation, not a product. We need to find a way to attach exactly the product variation to the field, for example, through ForeignKey, but based on variation_id.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question