I am working in a Python Eve based RESTful service with a SQLAlcemy backend. I have two models with a one to many relationship:
class User(CommonColumns):
"""Model of an user in the database"""
__tablename__ = "user"
id = Column(Integer, primary_key=True)
username = Column(String, unique=True)
email = Column(EmailType, unique=True)
folders = relationship('Folder', backref='user')
def __unicode__(self):
return self.username
class Folder(CommonColumns):
"""Model of an user in the database"""
__tablename__ = "folder"
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
user_id = Column(Integer, ForeignKey('user.id'), nullable=False)
def __unicode__(self):
return "{}/{}".format(self.user.username, self.name)
CommonColumns
is defined like here
This works great when inserting, updating and deleting users
. However, I can't get inserting right for folders
:
newfolder = {
'name':'FOLDER',
'user_id': 1,
}
response = requests.post("http://localhost:8080/api/v1.0/folders",data=newfolder)
print response.json()
{u'_error': {u'code': 422,
u'message': u'Insertion failure: 1 document(s) contain(s) error(s)'},
u'_issues': {u'exception': u"'user'"},
u'_status': u'ERR'}
Which is a rather cryptic error message. I've been reading Python Eve's documentation and I can't really understand what I am doing wrong. The only difference I see between user
and folder
insertions is that one has foreign keys.
Any idea why this is happening?
Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.
The comments class attribute defines a One-to-Many relationship between the Post model and the Comment model. You use the db. relationship() method, passing it the name of the comments model ( Comment in this case). You use the backref parameter to add a back reference that behaves like a column to the Comment model.
A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.
Well, it seemed that the problem was that I didn't have the same name for the resource and the table name ("users" for resource, "user" for table name). This seems to raise problems with foreign keys in eve, but does not fail with entities without relationships.
Changing the table names to match the resource names solved the problem.
I hope this will be useful to anyone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With