我必须在flask SQL alchemy中创建一个一对一的关系。我按照SO上的一些答案,发现我们必须定义
uselist=False
和
db.relationship
。但是当我在PGADMIN上看到ERD的时候,我看到的是一对多的关系。我的代码如下。
class Vehicle(db.Model):
__tablename__ = "vehicles"
id = db.Column(
db.String,
primary_key=True,
type = db.Column(
db.String,
nullable=False,
suspicious = db.Column(
db.Boolean,
nullable=False,
registered_user = db.relationship("Registered", backref="vehicles", uselist=False)
day_user = db.relationship("Visitor", backref="vehicles", uselist=False)
def __init__(self, type, suspicious):
self.type = type
self.suspicious = suspicious
def __repr__(self):
return "Vehicle(type='{}', suspicious={})".format(self.type, self.suspicious)
def serialize(self):
return {"id": self.id, "type": self.type, "suspicious": self.suspicious}
@classmethod
def from_json(cls, json):
return cls(json["type"], json["suspicious"])
class Registered(db.Model):
Registered User
__tablename__ = "registered"
regID = db.Column(db.String, primary_key=True)
name = db.Column(db.String, nullable=False)
cnic = db.Column(db.String, nullable=False)
contactNo = db.Column(db.String, nullable=False)
gender = db.Column(db.String, nullable=False)
DOR = db.Column(db.DateTime, nullable=False)
DOE = db.Column(db.DateTime, nullable=False)
vehicle_id = db.Column(db.String, db.ForeignKey("vehicles.id"), unique=True)
def __init__(self, name, cnic, contactNo, gender, DOR, DOE, vehicle_id):
self.name = name
self.cnic = cnic
self.contactNo = contactNo
self.gender = gender
self.DOR = DOR
self.DOE = DOE
self.vehicle_id = vehicle_id
def __repr__(self):
return "Registered(name='{}', cnic={},contactNo={},gender={},DOR={},DOE={})".format(
self.name,
self.cnic,
self.contactNo,
self.gender,
self.DOR,
self.DOE,
def serialize(self):
return {
"regID": self.regID,
"name": self.name,
"cnic": self.cnic,
"contactNo": self.contactNo,
"gender": self.gender,
"DOR": self.DOR,
"DOE": self.DOE,
@classmethod
def from_json(cls, json, vehicle_id):
return cls(
json["name"],
json["cnic"],
json["contactNo"],
json["gender"],
json["DOR"],
json["DOE"],
vehicle_id,
class Visitor(db.Model):
__tablename__ = "visitors"
id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True)
name = db.Column(db.String, nullable=False)
cnic = db.Column(db.String, nullable=False)
vehicle_id = db.Column(db.String, db.ForeignKey("vehicles.id"), unique=True)
def __init__(self, name, cnic, vehicle_id):
self.name = name
self.cnic = cnic
self.vehicle_id = vehicle_id
def __repr__(self):
return "Visitor(name='{}', cnic={})".format(self.name, self.cnic)
def serialize(self):
return {
"id": self.id,
"name": self.name,
"cnic": self.cnic,
if __name__ == "__main__":
db.create_all()
db.session.commit()