I have tables that I want to do an ORM based query.
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, server_default="1", nullable=False)
is_deleted = Column(Boolean, server_default="0", nullable=False)
created_at = Column(DateTime, nullable = False, default=func.now())
first_name = Column(String(30), nullable=False)
surname_name = Column(String(30), nullable=False)
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, server_default="1", nullable=False)
is_deleted = Column(Boolean, server_default="0", nullable=False)
created_at = Column(DateTime, nullable = False, default=func.now())
first_name = Column(String(30), nullable=False)
surname_name = Column(String(30), nullable=False)
appointments = relationship("ChildAppointment", backref="child")
class ParentChild(Base):
'''provides a many to many relationship for parent and child'''
__tablename__ = 'parent_child'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, nullable=False, server_default="1")
is_deleted = Column(Boolean, nullable=False, server_default="0")
parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)
child_id = Column(Integer, ForeignKey('child.id'))
parents = relationship("Parent", backref="parent_child")
children = relationship("Child", backref="parent_child")
class ChildAppointment(Base):
__tablename__ = 'child_appointment'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, nullable=False, server_default="1")
is_deleted = Column(Boolean, nullable=False, server_default="0")
created_at = Column(DateTime, nullable = False, default=func.now())
child_id = Column(Integer, ForeignKey('child.id'))
date_appointment = Column(DateTime, nullable = False)
I want to query Table ParentChild and through SQLAlchemy relationship magic, I want to get the latest appointment date for the child meaning I need the result ordered by date_appointment in the child table.
I have followed the example by #zeek here and I've come up with the following:
for data in session.query(ParentChild).join(Child.appointments).filter(ParentChild.parent_id == 1).\
order_by(Child.appointments.date_appointment.desc()).all():
However, I get the error attributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Child.appointments has an attribute 'date_appointment'
My scenario breaks what was given in that link because mine goes an extra table in as I have 4 tables so am unable to adapt his answer to suit mine.
Thanks.
Two things: First of all, for the join condition, you would want to specify it as a kind of chain:
ParentChild -> Child
Child -> ChildAppointment
That is done like this:
session.query(ParentChild).join(ParentChild.children).join(Child.appointments)
This will yield the correct join. I think if it is unambigous you could also do this:
session.query(ParentChild).join(Child).join(ChildAppointment)
But you'd have to try it out.
The real error, however, comes from this part:
Child.appointments.date_appointment
Instead it should look like this:
ChildAppointment.date_appointment
SQLAlchemy already knows how to get this ChildAppointment related to Child and ParentChild because you specified it in the joins above. And if you think about it in raw SQL terms it makes much more sense this way.
So you final solution:
session.query(ParentChild).join(ParentChild.children).join(Child.appointments).filter(ParentChild.parent_id == 1).order_by(ChildAppointment.date_appointment.desc()).all():
Related
How would you map a column that is not unique and is not a key into another schema(table)?
class TaskEntity(Base, BaseMixin):
__tablename__ = "task_entity"
__table_args__ = (UniqueConstraint("dag_no", "ordinal_position", name="dag_ordinal_uq_constraint"),)
task_no = Column(BIGINT(20), primary_key=True, autoincrement=True, nullable=False)
job_no = Column(BIGINT(20), ForeignKey("job_tb.job_no"), nullable=False)
task_name = Column(String(128), unique=True, nullable=False)
ordinal_position = Column(SMALLINT(6), nullable=False, default=1)
ordinal_position is not unique on its own, but is unique per task_no which is unique per job_no.
Ex) job_no.A can only have 1 of task_no.A which can only have 1 of ordinal_position.C. But job_no.B can have a task_no.A and ordinal_position.C.
I am trying to create the below schema in conjunction with class TaskEntity above, but am returning a "errno: 150 "Foreign key constraint is incorrectly formed" which I am assuing comes from the fact that ordinal_position is not unique.
class TaskLog(Base, BaseMixin):
__tablename__ = "task_log"
task_log_no = Column(BIGINT(20), nullable=False, autoincrement=True, primary_key=True)
execution_datetime = Column(TIMESTAMP, nullable=False)
start_datetime = Column(TIMESTAMP, nullable=False)
duration = Column(Float, nullable=False)
job_no = Column(BIGINT(20), ForeignKey("job_tb.job_no"), nullable=False)
task_no = Column(BIGINT(20), ForeignKey("task_entity.task_no"), nullable=False)
task_name = Column(String(128), ForeignKey("task_entity.task_name"), nullable=False)
# this is the declaration causing issues:
task_ordinal_position = Column(SMALLINT(6), ForeignKey("task_entity.ordinal_position"), nullable=False)
Have tried using relationships and "primary_join=", but the mapping seems to be very off once the data comes in.
Any inputs, much appreciated.
If I'm reading this correctly, then you probably want a UniqueConstraint across all three columns:
__table_args__ = (
UniqueConstraint('task_no', 'job_no', 'ordinal_position'),
)
I have a small base for a website for a real estate agency, below are two tables:
class Person(Base):
__tablename__ = "people"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
surname = Column(String, nullable=False)
city = Column(String, nullable=True)
# TODO - add lists
class Property(Base):
__tablename__ = "properties"
id = Column(Integer, primary_key=True, index=True)
city = Column(String, nullable=False)
address = Column(String, nullable=False)
owner_id = Column(Integer, ForeignKey("people.id"), nullable=False)
manager_id = Column(Integer, ForeignKey("people.id"), nullable=False)
# TODO - rework
owner = relationship("Person", foreign_keys=[owner_id], backref=backref("owners"))
manager = relationship("Person", foreign_keys=[manager_id], backref=backref("managers"))
I would like my 'Person' object to have two lists of properties - "owned_properites" and "properties_to_manage" (without losing reference to the owner/manager in the 'Property' class). But i don't know how to define a relationship to make auto mapping work properly.
If the class 'Property' only had one foreign key to the 'Person', for example - only "owner_id" key and "owner" object then it would be simple:
#in Property
owner_id = Column(Integer, ForeignKey("people.id"), nullable=False)
owner = relationship("Person", back_populates="property")
#in Person
owned_properties = relationship("Property", back_populates="owner")
But how to do the same with two keys, as shown at the beginning?
Table is this
class CustomGroups(Base):
__tablename__ = 'custom_groups'
id = Column(Integer, primary_key=True)
name = Column(String(80), unique=True, nullable=False)
last_used = Column(DateTime, default=datetime.utcnow())
created = Column(DateTime, default=datetime.utcnow())
images = relationship("Images", secondary=images_with_groups, back_populates="groups")
tags = relationship("Tags", secondary=custom_groups_with_tags, back_populates="groups")
children = relationship("CustomGroups", secondary='custom_groups_relationship',
primaryjoin='CustomGroups.id==CustomGroupsRelationship.parent_id',
secondaryjoin="CustomGroups.id==CustomGroupsRelationship.child_id",
backref="parent")
Relationship table
class CustomGroupsRelationship(Base):
__tablename__ = 'custom_groups_relationship'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('custom_groups.id'))
child_id = Column(Integer, ForeignKey('custom_groups.id'))
created_at = Column(DateTime, default=datetime.now())
updated_at = Column(DateTime, default=datetime.now())
I want to have UniqueConstraint on CustomGroups.name and CustomGroups.parent at sametime.
But also when they are on same level, there shouldn't be duplicate names, similar to windows folder structure.
Thanks
I have these 3 sql alchemy (sqla) models:
class Site(Base):
__tablename__ = "site"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow())
updated_at = Column(DateTime, nullable=True, default=datetime.utcnow(), onupdate=datetime.utcnow)
class Camera(Base):
__tablename__ = "camera"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
site_id = Column(UUID(as_uuid=True), ForeignKey("site.id"), nullable=False)
name = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow())
updated_at = Column(DateTime, nullable=True, default=datetime.utcnow(), onupdate=datetime.utcnow)
site = relationship("Site", backref="cameras")
class RtspServerEndpoint(Base):
__tablename__ = "rtsp_server_endpoint"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
camera_id = Column(UUID(as_uuid=True), ForeignKey("camera.id"), nullable=False)
rtsp_url_endpoint = Column(String, nullable=False)
rtsp_username = Column(String, nullable=False)
rtsp_encrypted_password = Column(String, nullable=False)
name = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow())
updated_at = Column(DateTime, nullable=True, default=datetime.utcnow(), onupdate=datetime.utcnow)
camera = relationship("Camera", backref="rtsp_server_endpoint", lazy="joined")
camera_id is the foreign key of rtspserverendpoint table and site_id is the foreign key for the Camera table.
When a user wants to add a new rtspserverendpoint record, he makes an HTTP request such as:
POST sites/<site_id>/camera/<camera_id>/rtspserverendpoint
Before adding the new rtspserverendpoint, I would like to make sure that the <site_id> and the <camera_id> are consistent, as a security. I can probably make a separate query just to check that, such as:
check_record_exist = db.session.query(Camera).filter(Camera.site_id == site_id).first()
if not check_record_exist:
raise ("No such camera with this site_id")
But what I would like to know, is if there is a more elegant way to check that: For example, adding a constraint in my Base models that would forbid adding such an inconsistent record in the database.
I am not aware of any straightforward way to implement this 2-level check on the database directly.
In fact, the only consistency that the database should know about is that your new RtspServerEndpoint instance will belong to the correct Camera instance. But this will be correct by default by the way you will be creating the RtspServerEndpoint instance.
Therefore, in my opinion, the check of the correctness of the site_id in the URL of the POST request should be implemented in the logic of your code. I would probably do it along these lines:
#handler(..., method='POST')
def rtspserverendpoint(site_id: int, camera_id: int):
# find camera, which will allow us to check the correctness of the site_id as well
camera = db.session.query(Camera).get(camera_id)
if camera is None:
raise Exception(f"No camera with this {camera_id=}.")
if camera.site_id != site_id:
raise Exception(f"Camera with this {camera_id=} does not belong to the site with {site_id=}.")
new_obj = RtspServerEndpoint(
...,
camera_id=camera_id,
...,
)
db.session.add(new_obj)
db.session.commit()
I am coming from a python-django and am trying to get a grasp on flask-SQLAlchemy:
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(128), nullable=False)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(128), nullable=False)
author = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False)
I want to get a joined result list:
results = Book.query.filter(Author.name=='tom')
for result in results:
print(result.title, result.???.name)
How do I access the fields of the joined tables?
I figured it out:
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(128), nullable=False)
author_id = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False)
author = relationship("Author")
I needed to add the line
author = relationship("Author")
to the model. It seems to be necessary to declare the relationship on the object level. I did miss this.
Now the line can be:
print(result.title, result.author.name)