Cannot get a many to many relationship to properly work using SQLAlchemy











up vote
0
down vote

favorite
1












I've got 3 tables; user, location and location_favorite.
location_favorite being kind of like a association table. I'm trying to be able to create a list of favorite locations forf the user using that table.



user class looks like this:



import datetime
from sqlalchemy import Column, Integer, String, Date, ForeignKey
from sqlalchemy.orm import relationship

from model import Base
from model.address import Address
from model.group import Group
from model.location_favorite import LocationFavorite


class User(Base):
__tablename__ = 'users'
id = Column(Integer, nullable=False, unique=True, primary_key=True)
username = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
reset_token = Column(String, default=None)
email = Column(String, nullable=False, unique=True)
account_status = Column(Integer, nullable=False, default=0)
user_group = Column(Integer, ForeignKey("user_groups.id"),
nullable=False, default=1)
registration_date = Column(Date, nullable=False,
default=datetime.datetime.now())
last_online = Column(Date, default=datetime.datetime.now())


# Relationships
address = relationship(Address, uselist=False, back_populates="user")
group = relationship(Group, back_populates='users')
spots = relationship("Location")
favorite_spots = relationship('Location', secondary='location_favorite',
backref='favorited_by')


location class looks like this:



class Location(Base):
__tablename__ = 'location'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, unique=True)
description = Column(String, nullable=False)
creator_id = Column(Integer, ForeignKey('users.id'))
latitude = Column(Float)
longtitude = Column(Float)
creation_date = Column(Date, default=datetime.now)

# Relationships
creator = relationship('User', foreign_keys=creator_id,
back_populates='spots')
events = relationship('Event')
favorited_by = relationship('User', secondary='location_favorite',
backref='favorite_spots')


and the location_favorite class looks like this:



class LocationFavorite(Base):
__tablename__ = 'location_favorite'
user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
location_id = Column(Integer, ForeignKey('location.id'),
primary_key=True)
creation_date = Column(Date, default=datetime.now)


Now that gives me the following exception:



Could not determine join condition between parent/child tables on 
relationship User.favorite_spots


I suppose that is a logical response because the user doesn't have any reference to location_favorite except for the user_id.. which is a part of a composite primary key. I just can't figure out what would be the best way to create this relationship.










share|improve this question
























  • Not sure if this is the root of the problem but you are using the backref keyword parameter for User.favorite_spots and Location.favorited_by even though you are defining the relationship on both sides. Should use back_populates. I don’t know that that fixes your original issue but just something that stands out to me.
    – SuperShoot
    Nov 17 at 11:30










  • Mmh that doesn't seem to fix the issue, I thought back_populates did the same as backref.
    – Azrael
    Nov 17 at 18:13






  • 1




    backref is a shortcut for placing the relationship on both sides. Define relationship on one one side with backref, and it will be available on other side with the attribute name being whatever you passed to backref parameter. docs.sqlalchemy.org/en/latest/orm/backref.html. Sorry it didn’t solve your issue but just stood out to me when I read your question and I wasn’t around a computer to test.
    – SuperShoot
    Nov 17 at 20:08






  • 1




    So the actual issue is that you define your FK on LocationFavorite.user_id as ForeignKey('user.id'), but User.__tablename__ = 'users', so FK should be ForeignKey('users.id'). Fix that and then you'll see the problem with using backref after defining the relationship on both sides.
    – SuperShoot
    Nov 17 at 22:21








  • 1




    Awesome! That indeed fixed my issue, thanks!
    – Azrael
    Nov 18 at 10:41















up vote
0
down vote

favorite
1












I've got 3 tables; user, location and location_favorite.
location_favorite being kind of like a association table. I'm trying to be able to create a list of favorite locations forf the user using that table.



user class looks like this:



import datetime
from sqlalchemy import Column, Integer, String, Date, ForeignKey
from sqlalchemy.orm import relationship

from model import Base
from model.address import Address
from model.group import Group
from model.location_favorite import LocationFavorite


class User(Base):
__tablename__ = 'users'
id = Column(Integer, nullable=False, unique=True, primary_key=True)
username = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
reset_token = Column(String, default=None)
email = Column(String, nullable=False, unique=True)
account_status = Column(Integer, nullable=False, default=0)
user_group = Column(Integer, ForeignKey("user_groups.id"),
nullable=False, default=1)
registration_date = Column(Date, nullable=False,
default=datetime.datetime.now())
last_online = Column(Date, default=datetime.datetime.now())


# Relationships
address = relationship(Address, uselist=False, back_populates="user")
group = relationship(Group, back_populates='users')
spots = relationship("Location")
favorite_spots = relationship('Location', secondary='location_favorite',
backref='favorited_by')


location class looks like this:



class Location(Base):
__tablename__ = 'location'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, unique=True)
description = Column(String, nullable=False)
creator_id = Column(Integer, ForeignKey('users.id'))
latitude = Column(Float)
longtitude = Column(Float)
creation_date = Column(Date, default=datetime.now)

# Relationships
creator = relationship('User', foreign_keys=creator_id,
back_populates='spots')
events = relationship('Event')
favorited_by = relationship('User', secondary='location_favorite',
backref='favorite_spots')


and the location_favorite class looks like this:



class LocationFavorite(Base):
__tablename__ = 'location_favorite'
user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
location_id = Column(Integer, ForeignKey('location.id'),
primary_key=True)
creation_date = Column(Date, default=datetime.now)


Now that gives me the following exception:



Could not determine join condition between parent/child tables on 
relationship User.favorite_spots


I suppose that is a logical response because the user doesn't have any reference to location_favorite except for the user_id.. which is a part of a composite primary key. I just can't figure out what would be the best way to create this relationship.










share|improve this question
























  • Not sure if this is the root of the problem but you are using the backref keyword parameter for User.favorite_spots and Location.favorited_by even though you are defining the relationship on both sides. Should use back_populates. I don’t know that that fixes your original issue but just something that stands out to me.
    – SuperShoot
    Nov 17 at 11:30










  • Mmh that doesn't seem to fix the issue, I thought back_populates did the same as backref.
    – Azrael
    Nov 17 at 18:13






  • 1




    backref is a shortcut for placing the relationship on both sides. Define relationship on one one side with backref, and it will be available on other side with the attribute name being whatever you passed to backref parameter. docs.sqlalchemy.org/en/latest/orm/backref.html. Sorry it didn’t solve your issue but just stood out to me when I read your question and I wasn’t around a computer to test.
    – SuperShoot
    Nov 17 at 20:08






  • 1




    So the actual issue is that you define your FK on LocationFavorite.user_id as ForeignKey('user.id'), but User.__tablename__ = 'users', so FK should be ForeignKey('users.id'). Fix that and then you'll see the problem with using backref after defining the relationship on both sides.
    – SuperShoot
    Nov 17 at 22:21








  • 1




    Awesome! That indeed fixed my issue, thanks!
    – Azrael
    Nov 18 at 10:41













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





I've got 3 tables; user, location and location_favorite.
location_favorite being kind of like a association table. I'm trying to be able to create a list of favorite locations forf the user using that table.



user class looks like this:



import datetime
from sqlalchemy import Column, Integer, String, Date, ForeignKey
from sqlalchemy.orm import relationship

from model import Base
from model.address import Address
from model.group import Group
from model.location_favorite import LocationFavorite


class User(Base):
__tablename__ = 'users'
id = Column(Integer, nullable=False, unique=True, primary_key=True)
username = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
reset_token = Column(String, default=None)
email = Column(String, nullable=False, unique=True)
account_status = Column(Integer, nullable=False, default=0)
user_group = Column(Integer, ForeignKey("user_groups.id"),
nullable=False, default=1)
registration_date = Column(Date, nullable=False,
default=datetime.datetime.now())
last_online = Column(Date, default=datetime.datetime.now())


# Relationships
address = relationship(Address, uselist=False, back_populates="user")
group = relationship(Group, back_populates='users')
spots = relationship("Location")
favorite_spots = relationship('Location', secondary='location_favorite',
backref='favorited_by')


location class looks like this:



class Location(Base):
__tablename__ = 'location'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, unique=True)
description = Column(String, nullable=False)
creator_id = Column(Integer, ForeignKey('users.id'))
latitude = Column(Float)
longtitude = Column(Float)
creation_date = Column(Date, default=datetime.now)

# Relationships
creator = relationship('User', foreign_keys=creator_id,
back_populates='spots')
events = relationship('Event')
favorited_by = relationship('User', secondary='location_favorite',
backref='favorite_spots')


and the location_favorite class looks like this:



class LocationFavorite(Base):
__tablename__ = 'location_favorite'
user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
location_id = Column(Integer, ForeignKey('location.id'),
primary_key=True)
creation_date = Column(Date, default=datetime.now)


Now that gives me the following exception:



Could not determine join condition between parent/child tables on 
relationship User.favorite_spots


I suppose that is a logical response because the user doesn't have any reference to location_favorite except for the user_id.. which is a part of a composite primary key. I just can't figure out what would be the best way to create this relationship.










share|improve this question















I've got 3 tables; user, location and location_favorite.
location_favorite being kind of like a association table. I'm trying to be able to create a list of favorite locations forf the user using that table.



user class looks like this:



import datetime
from sqlalchemy import Column, Integer, String, Date, ForeignKey
from sqlalchemy.orm import relationship

from model import Base
from model.address import Address
from model.group import Group
from model.location_favorite import LocationFavorite


class User(Base):
__tablename__ = 'users'
id = Column(Integer, nullable=False, unique=True, primary_key=True)
username = Column(String, nullable=False, unique=True)
password = Column(String, nullable=False)
reset_token = Column(String, default=None)
email = Column(String, nullable=False, unique=True)
account_status = Column(Integer, nullable=False, default=0)
user_group = Column(Integer, ForeignKey("user_groups.id"),
nullable=False, default=1)
registration_date = Column(Date, nullable=False,
default=datetime.datetime.now())
last_online = Column(Date, default=datetime.datetime.now())


# Relationships
address = relationship(Address, uselist=False, back_populates="user")
group = relationship(Group, back_populates='users')
spots = relationship("Location")
favorite_spots = relationship('Location', secondary='location_favorite',
backref='favorited_by')


location class looks like this:



class Location(Base):
__tablename__ = 'location'
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, unique=True)
description = Column(String, nullable=False)
creator_id = Column(Integer, ForeignKey('users.id'))
latitude = Column(Float)
longtitude = Column(Float)
creation_date = Column(Date, default=datetime.now)

# Relationships
creator = relationship('User', foreign_keys=creator_id,
back_populates='spots')
events = relationship('Event')
favorited_by = relationship('User', secondary='location_favorite',
backref='favorite_spots')


and the location_favorite class looks like this:



class LocationFavorite(Base):
__tablename__ = 'location_favorite'
user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
location_id = Column(Integer, ForeignKey('location.id'),
primary_key=True)
creation_date = Column(Date, default=datetime.now)


Now that gives me the following exception:



Could not determine join condition between parent/child tables on 
relationship User.favorite_spots


I suppose that is a logical response because the user doesn't have any reference to location_favorite except for the user_id.. which is a part of a composite primary key. I just can't figure out what would be the best way to create this relationship.







python sqlalchemy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 at 12:40









davidism

60.8k12153173




60.8k12153173










asked Nov 17 at 10:41









Azrael

954618




954618












  • Not sure if this is the root of the problem but you are using the backref keyword parameter for User.favorite_spots and Location.favorited_by even though you are defining the relationship on both sides. Should use back_populates. I don’t know that that fixes your original issue but just something that stands out to me.
    – SuperShoot
    Nov 17 at 11:30










  • Mmh that doesn't seem to fix the issue, I thought back_populates did the same as backref.
    – Azrael
    Nov 17 at 18:13






  • 1




    backref is a shortcut for placing the relationship on both sides. Define relationship on one one side with backref, and it will be available on other side with the attribute name being whatever you passed to backref parameter. docs.sqlalchemy.org/en/latest/orm/backref.html. Sorry it didn’t solve your issue but just stood out to me when I read your question and I wasn’t around a computer to test.
    – SuperShoot
    Nov 17 at 20:08






  • 1




    So the actual issue is that you define your FK on LocationFavorite.user_id as ForeignKey('user.id'), but User.__tablename__ = 'users', so FK should be ForeignKey('users.id'). Fix that and then you'll see the problem with using backref after defining the relationship on both sides.
    – SuperShoot
    Nov 17 at 22:21








  • 1




    Awesome! That indeed fixed my issue, thanks!
    – Azrael
    Nov 18 at 10:41


















  • Not sure if this is the root of the problem but you are using the backref keyword parameter for User.favorite_spots and Location.favorited_by even though you are defining the relationship on both sides. Should use back_populates. I don’t know that that fixes your original issue but just something that stands out to me.
    – SuperShoot
    Nov 17 at 11:30










  • Mmh that doesn't seem to fix the issue, I thought back_populates did the same as backref.
    – Azrael
    Nov 17 at 18:13






  • 1




    backref is a shortcut for placing the relationship on both sides. Define relationship on one one side with backref, and it will be available on other side with the attribute name being whatever you passed to backref parameter. docs.sqlalchemy.org/en/latest/orm/backref.html. Sorry it didn’t solve your issue but just stood out to me when I read your question and I wasn’t around a computer to test.
    – SuperShoot
    Nov 17 at 20:08






  • 1




    So the actual issue is that you define your FK on LocationFavorite.user_id as ForeignKey('user.id'), but User.__tablename__ = 'users', so FK should be ForeignKey('users.id'). Fix that and then you'll see the problem with using backref after defining the relationship on both sides.
    – SuperShoot
    Nov 17 at 22:21








  • 1




    Awesome! That indeed fixed my issue, thanks!
    – Azrael
    Nov 18 at 10:41
















Not sure if this is the root of the problem but you are using the backref keyword parameter for User.favorite_spots and Location.favorited_by even though you are defining the relationship on both sides. Should use back_populates. I don’t know that that fixes your original issue but just something that stands out to me.
– SuperShoot
Nov 17 at 11:30




Not sure if this is the root of the problem but you are using the backref keyword parameter for User.favorite_spots and Location.favorited_by even though you are defining the relationship on both sides. Should use back_populates. I don’t know that that fixes your original issue but just something that stands out to me.
– SuperShoot
Nov 17 at 11:30












Mmh that doesn't seem to fix the issue, I thought back_populates did the same as backref.
– Azrael
Nov 17 at 18:13




Mmh that doesn't seem to fix the issue, I thought back_populates did the same as backref.
– Azrael
Nov 17 at 18:13




1




1




backref is a shortcut for placing the relationship on both sides. Define relationship on one one side with backref, and it will be available on other side with the attribute name being whatever you passed to backref parameter. docs.sqlalchemy.org/en/latest/orm/backref.html. Sorry it didn’t solve your issue but just stood out to me when I read your question and I wasn’t around a computer to test.
– SuperShoot
Nov 17 at 20:08




backref is a shortcut for placing the relationship on both sides. Define relationship on one one side with backref, and it will be available on other side with the attribute name being whatever you passed to backref parameter. docs.sqlalchemy.org/en/latest/orm/backref.html. Sorry it didn’t solve your issue but just stood out to me when I read your question and I wasn’t around a computer to test.
– SuperShoot
Nov 17 at 20:08




1




1




So the actual issue is that you define your FK on LocationFavorite.user_id as ForeignKey('user.id'), but User.__tablename__ = 'users', so FK should be ForeignKey('users.id'). Fix that and then you'll see the problem with using backref after defining the relationship on both sides.
– SuperShoot
Nov 17 at 22:21






So the actual issue is that you define your FK on LocationFavorite.user_id as ForeignKey('user.id'), but User.__tablename__ = 'users', so FK should be ForeignKey('users.id'). Fix that and then you'll see the problem with using backref after defining the relationship on both sides.
– SuperShoot
Nov 17 at 22:21






1




1




Awesome! That indeed fixed my issue, thanks!
– Azrael
Nov 18 at 10:41




Awesome! That indeed fixed my issue, thanks!
– Azrael
Nov 18 at 10:41

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53350431%2fcannot-get-a-many-to-many-relationship-to-properly-work-using-sqlalchemy%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53350431%2fcannot-get-a-many-to-many-relationship-to-properly-work-using-sqlalchemy%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

"Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

Alcedinidae

RAC Tourist Trophy