编码:
class Customers(db.Model):
customerid = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(30), nullable=False)
lastname = db.Column(db.String(30), nullable =False)
address = db.Column(db.String(30), nullable =False)
city = db.Column(db.String(30), nullable =False)
postalcode = db.Column(db.String(30), nullable =False)
region = db.Column(db.String(30), nullable =False)
country = db.Column(db.String(30), nullable =False)
email = db.Column(db.String(), nullable =False)
creditcard = db.Column(db.Integer, nullable =False)
class Orders(db.Model):
orderid = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
# foreign key (customers.customerid)
class Products(db.Model):
productid = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30), nullable=False)
price = db.Column(db.Float(), nullable=False)
description = db.Column(db.Text())
image = db.Column(db.String(20), nullable=False)
units = db.Column(db.Integer, nullable=False)
class OrderDetails(db.Model):
# composite primary key consisting of two foreign keys (order.orderid, products.productid)
quantity = db.Column(db.Integer, nullable=False)
两个问题:
1)
我正在尝试在“订单”表中创建单个外键,这是“客户”表(customerid)的主键以链接这两个表,因为单个客户可以有很多订单。
2)
我正在尝试在“ OrderDetails”表中创建一个复合主键(两个外键),该表由“订单”表的主键(orderid)和“产品”表的主键(productid)组成。
I have trouble understanding when to use backref
and back_populates
and how to use these with db.Relationship()
. And I have trouble using db.ForeignKeyConstraint(['productid', 'orderid'],['products.productid','orders.orderid'])
for the composite primary key.
我该如何解决这两个问题?