Created
December 4, 2014 20:27
-
-
Save rcalsaverini/95a6a6bb5c06fb2a2a65 to your computer and use it in GitHub Desktop.
SQLAlchemy join on composite key, can't make it work... :(
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
from flask import Flask | |
from flask.ext.sqlalchemy import SQLAlchemy | |
app = Flask(__name__) | |
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' | |
# app.config['SQLALCHEMY_BINDS'] = { | |
# 'users': 'mysqldb://localhost/users', | |
# 'appmeta': 'sqlite:////path/to/appmeta.db' | |
# } | |
db = SQLAlchemy(app) | |
class Asset(db.Model): | |
__tablename__ = 'asset' | |
user = db.Column('usuario', db.Integer, primary_key=True) | |
profile = db.Column('perfil', db.Integer, primary_key=True) | |
name = db.Column('nome', db.Unicode(255)) | |
def __str__(self): | |
return u"Asset({}, {}, {})".format(self.user, self.profile, self.name).encode('utf-8') | |
class Zabumba(db.Model): | |
__tablename__ = 'zabumba' | |
db.ForeignKeyConstraint( | |
['asset.user', 'asset.profile'], | |
['zabumba.user', 'zabumba.profile'] | |
) | |
user = db.Column('usuario', db.Integer, primary_key=True) | |
profile = db.Column('perfil', db.Integer, primary_key=True) | |
count = db.Column('qtdade', db.Integer) | |
def __str__(self): | |
return u"Zabumba({}, {}, {})".format(self.user, self.profile, self.count).encode('utf-8') | |
db.drop_all() | |
db.create_all() | |
db.session.add(Asset(user=1, profile=1, name=u"Pafúncio")) | |
db.session.add(Asset(user=1, profile=2, name=u"Skavurska")) | |
db.session.add(Asset(user=2, profile=1, name=u"Ermengarda")) | |
db.session.add(Zabumba(user=1, profile=1, count=10)) | |
db.session.add(Zabumba(user=1, profile=2, count=11)) | |
db.session.add(Zabumba(user=2, profile=1, count=12)) | |
db.session.commit() | |
print "ALL:" | |
for asset, zabumba in db.session.query(Asset, Zabumba).all(): | |
print "{:25}\t<---->\t{:25}".format(asset, zabumba) | |
print "Attempt 1:" | |
for asset, zabumba in db.session.query(Zabumba).join(Asset).all(): | |
print "{:25}\t<---->\t{:25}".format(asset, zabumba) | |
print "Attempt 2:" | |
for asset, zabumba in db.session.query(Asset).join(Zabumba).all(): | |
print "{:25}\t<---->\t{:25}".format(asset, zabumba) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment