I have the following definitions
class Usuario(db.Model):
__tablename__ = 'usuarios'
id_usuario = db.Column(db.Integer, primary_key = True)
id_centro = db.Column(db.Integer)
creado_en = db.Column(db.DateTime)
actualizado_en = db.Column(db.DateTime)
gcm_id = db.Column(db.Text)
notificaciones = db.relationship('RelNotificacionUsuario', backref='usuario', lazy='dynamic')
def __init__(self, id_usuario, id_centro):
self.id_usuario = id_usuario.title()
self.id_centro = id_centro.title()
self.gcm_id = gcm_id.title()
class Notificaciones(db.Model):
__tablename__ = 'notificaciones'
id_notificacion = db.Column(db.Integer, primary_key = True)
descripcion = db.Column(db.Text)
creado_en = db.Column(db.DateTime)
actualizado_en = db.Column(db.DateTime)
fecha = db.Column(db.DateTime)
notificaciones = db.relationship('RelNotificacionUsuario', backref='notificacion', lazy='dynamic')
def __init__(self, id_usuario, id_centro):
self.id_usuario = id_usuario.title()
self.id_centro = id_centro.title()
self.gcm_id = gcm_id.title()
class RelNotificacionUsuario(db.Model):
__tablename__ = 'rel_notificacion_usuario'
id_usuario = db.Column(db.Integer, primary_key = True, db.ForeignKey('usuarios.id_usuario'))
id_centro = db.Column(db.Integer, primary_key = True, db.ForeignKey('notificaciones.id_notificacion'))
creado_en = db.Column(db.DateTime)
actualizado_en = db.Column(db.DateTime)
gcm_id = db.Column(db.Text)
Well the following lines are failing SyntaxError: non-keyword arg after keyword arg
id_usuario = db.Column(db.Integer, primary_key = True, db.ForeignKey('usuarios.id_usuario'))
id_centro = db.Column(db.Integer, primary_key = True, db.ForeignKey('notificaciones.id_notificacion'))
According to docs http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.Column
This is the good way:
id_usuario = db.Column(db.Integer, db.ForeignKey('usuarios.id_usuario'), primary_key = True)
id_centro = db.Column(db.Integer, db.ForeignKey('notificaciones.id_notificacion'), primary_key = True)
Related
I have two tables:
class Ticket(db.Model):
ticketID = db.Column(db.Integer, primary_key=True)
uidCreator = db.Column(db.Integer, db.ForeignKey("User.id"))
uidEmployee = db.Column(db.Integer, db.ForeignKey("User.id"))
ticketType = db.Column(db.String(50))
ticketComments = db.Column(db.String(500))
empTicketComments = db.Column(db.String(500))
empDateRespond = db.Column(db.DateTime(timezone=True))
empDateTaken = db.Column(db.DateTime(timezone=True))
dateCreated = db.Column(db.DateTime(timezone=True), default=func.now())
dateResolved = db.Column(db.DateTime(timezone=True))
Status = db.Column(db.String(24))
department =
And
class DepartmentTickets(db.Model):
id = db.Column(db.Integer(), primary_key=True)
department = db.Column(db.String(100))
ticketType = db.Column(db.String(100), unique=True)
How can I return the department for my Ticket.department column where Ticket.ticketType == DepartmentTickets.ticketType ?
When I then send the query, neither the BSM_ID nor the employee field are displayed.
I have the following models:
class Bprojpod(db.Model):
__tablename__ = 'BPROJPOD'
ID = db.Column(db.Integer, primary_key=True)
ZEIT_VON = db.Column(db.String)
ZEIT_BIS = db.Column(db.String)
PAUSE = db.Column(db.String)
BSM_ID = db.Column(db.Integer, ForeignKey("BSM.ID"))
EMPLOYEE = relationship("Bsm", foreign_keys=[BSM_ID])
BTICK_ID = db.Column(db.Integer)
class Bsm(db.Model):
__tablename__ = "BSM"
ID = db.Column(db.Integer, primary_key=True)
NAME = db.Column(db.String)
class BprojpodSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Bprojpod
load_instance = True
sqla_session = db.session
bprojpod_schema = BprojpodSchema()
abprojpod_schema = BprojpodSchema(many=True)
This is how I call the query:
def getBprojpod(btick_id):
abprojpod = Bprojpod.query.filter(Bprojpod.BTICK_ID == btick_id).all()
return abprojpod_schema.dump(abprojpod)
Can someone explain to me what I'm doing wrong?
AFAIK merge performs and insert or update so what I'm doing is pretty simple.
There is a relation of 1 to N between Hubs and Tags.
So when I try to make a merge on tag and hub, hub goes well and load from DB the existent hub and make an update, but fails when db.session.merge(nuevo_tag) is executed throwing an exception because behind the scenes tries to make an insert, even if the tag previously exist.
What I did wrong?
nuevo_hub = Hub(guid_hub,name,location,comments,id_project,creado_en,actualizado_en)
merged_hub = db.session.merge(nuevo_hub)
#db.session.commit() # If I use this line tags perform an insert.
nuevo_tag = Tag(guid_tag,project,merged_hub,TYPE_HUB,creado_en,actualizado_en)
merged_tag = db.session.merge(nuevo_tag)
db.session.commit()
If I remove db.session.commit() then other error is shown:
sqlalchemy.orm.exc.FlushError: New instance with
identity key (,
(b'\x11\x0e\x84\x00\xe2\x9b\x11\xd4\xa7\x16DfUD\x00\r',)) conflicts
with persistent instance
class Item(db.Model):
__tablename__ = "items"
# id_item = db.Column(db.Integer, autoincrement=True, primary_key=True)
guid_item = db.Column(db.BINARY(16), primary_key=True)
id_project = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
type = db.Column(db.Integer)
name = db.Column(db.String(50), nullable=False, index= True)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
__mapper_args__ = {
'polymorphic_identity': 'items',
'polymorphic_on':type,
'with_polymorphic':'*'
}
__table_args__ = (
db.UniqueConstraint('name', 'id_project', name='_unique_name_project'),
)
def __init__(self,creado_en=None):
self.created_at = creado_en
self.updated_at = creado_en
class Hub(Item):
__tablename__ = "hubs"
__mapper_args__ = {
'polymorphic_identity': TYPE_HUB,
'with_polymorphic':'*'
}
guid_hub = db.Column(db.BINARY(16), db.ForeignKey(Item.guid_item), primary_key=True)
location = db.Column(db.String(50))
comments = db.Column(db.String(128))
def __init__(self, guid_hub=None, nombre=None, location=None,comments=None, id_project=None, creado_en=None, actualizado_en=None):
self.type = TYPE_HUB
self.guid_item = guid_hub
self.guid_hub = guid_hub
self.name = nombre
self.id_project = id_project
self.location = location
self.comments = comments
self.created_at = creado_en
self.updated_at = actualizado_en
class Tag(db.Model):
__tablename__ = "tags"
guid_tag = db.Column(db.BINARY(16), primary_key=True)
id_project = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
guid_item = db.Column(db.BINARY(16),db.ForeignKey("items.guid_item"))
project = db.relationship(Proyecto, backref=db.backref('list_tags', lazy='dynamic'))
item = db.relationship(Item, backref=db.backref('list_tags', lazy='joined'))
type = db.Column(db.Integer) #(0,hub);(1,cable);(2,pipe);(3,electrical_pipes)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
def __init__(self,guid_tag,project,item,type,created_at,updated_at):
# self.guid_item = guid_tag
self.guid_tag = guid_tag
self.project = project
self.item = item
self.type = type
self.created_at = created_at
self.updated_at = updated_at
I found the answer in docs.
Consider Hub is a subclass of Item.
I have to change backref lazy from joined to dynamic.
class Tag(db.Model):
__tablename__ = "tags"
guid_tag = db.Column(db.BINARY(16), primary_key=True)
id_project = db.Column(db.Integer,db.ForeignKey("projects.id_project"))
guid_item = db.Column(db.BINARY(16),db.ForeignKey("items.guid_item"))
project = db.relationship(Proyecto, backref=db.backref('list_tags', lazy='dynamic'))
item = db.relationship(Item, backref=db.backref('list_tags', lazy='joined'))
type = db.Column(db.Integer) #(0,hub);(1,cable);(2,pipe);(3,electrical_pipes)
created_at = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime)
In other words I must avoid have two copys of a persistence object in the same session.
I use SQLAlchemy not so long.
I have that structure:
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(140))
parent_id = db.Column(db.Integer, db.ForeignKey('category.id'))
parent = db.relationship("Category", remote_side=id, backref="sub_categories")
def __repr__(self):
return '<Category: {0.name}>'.format(self)
class Object(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(140))
category_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False)
category = db.relationship('Category', backref="objects")
values = db.relationship("Value", secondary="object_value", backref="objects")
def __repr__(self):
return '<Object: {0.name}>'.format(self)
class Property(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(140))
categories = db.relationship("Category", secondary="category_property", backref="properties")
def __repr__(self):
return '<Property: {0.name}>'.format(self)
class Value(db.Model):
id = db.Column(db.Integer, primary_key=True)
value = db.Column(db.String(140))
property_id = db.Column(db.Integer, db.ForeignKey("property.id"))
prop = db.relationship('Property', backref="values")
def __repr__(self):
return '<Value: {0.prop.name}={0.value}>'.format(self)
db.Table(
'category_property', db.Model.metadata,
db.Column('category_id', db.Integer, db.ForeignKey('category.id')),
db.Column('property_id', db.Integer, db.ForeignKey('property.id'))
)
db.Table(
'object_value', db.Model.metadata,
db.Column('object_id', db.Integer, db.ForeignKey('object.id')),
db.Column('value_id', db.Integer, db.ForeignKey('value.id'))
)
Used this I try to get all objects for category, but in objects I want to get only property which used in category. I mean some like that:
category = Category(name="Category")
category_property = Property(name="Category Property")
category.properties.append(category_property)
value_category_property = Value(prop=category_property, value="value")
other_property = Property(name="Other Property")
value_other_property = Value(prop=other_property, value="value")
obj = Object(name="Entry", category=category)
obj.values.append(value_category_property)
obj.values.append(value_other_property)
db.session.add(obj)
db.session.commit()
for obj in db.session.query(Object)\
.some_join_subquery()\
.filter(Object.category == category.id)\
.all():
assert value_category_property in obj.values
assert value_other_property not in obj.values
What must be in some_join_subquery?
Use the any query property of relationships.
Object.query.filter(
Object.category_id == category.id,
Object.values.any(name == 'Category Property'),
db.not_(Object.values.any(name == 'Other Property'))
)
I have the following entities. When I do api/event/1, I get the invitation included, but not the invitationResponses. If, and how, is this possible to achieve?
When I do api/invitation/1 the invitationResponses are included.
class Person(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), index = True)
owner = db.Column(db.Integer, db.ForeignKey('user.id'))
description = db.Column(db.String(128))
start = db.Column(db.DateTime)
end = db.Column(db.DateTime)
invitation = db.relationship('Invitation', uselist=False, backref = db.backref('event', uselist=False))
class Invitation(db.Model):
id = db.Column(db.Integer, primary_key = True)
event_id = db.Column(db.Integer, db.ForeignKey('event.id'))
sent = db.Column(db.DateTime)
expires = db.Column(db.DateTime)
invitationResponses = db.relationship('InvitationResponse', backref = db.backref('invitation', uselist=False))
class InvitationResponse(db.Model):
id = db.Column(db.Integer, primary_key = True)
invitation_id = db.Column(db.Integer, db.ForeignKey('invitation.id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
attending = db.Column(db.Boolean)