Reputation: 3712
I am using this tutorial as a guideline. http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
I want to have Categories that can heave multiple Products. Similar to how he has a User with multiple Posts.
when I open up the python interpreter and try to create a category
>>>from app import db, models
>>>u = models.Category(name="Test")
I get this error
/sqlalchemy/orm/properties.py", line 1387, in _generate_backref
self, mapper))
sqlalchemy.exc.ArgumentError: Error creating backref 'category' on relationship 'Category.products': property of that name exists on mapper 'Mapper|Product|product'
So there is a problem with the backref. In the tutorial (and I have tried it with his code) he is able to make a User with similar syntax.
I even tried using all of his files and created and migrated a new database and I get the same error.
Here is my models.py file:
from app import db
WR_IP_NO = 0
WR_IP_YES = 1
class Category(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64), unique = True)
products = db.relationship('Product', backref = 'category', lazy = 'dynamic')
def __repr__(self):
return '<Category %r>' % (self.name)
class Product(db.Model):
id = db.Column(db.Integer, primary_key = True)
category = db.Column(db.String(64), db.ForeignKey('category.id'))
courseName = db.Column(db.String(120), unique = True)
ip = db.Column(db.SmallInteger, default = WR_IP_YES)
duration = db.Column(db.Integer)
productRev = db.Column(db.String(64))
#use when database is updated?
releaseDate = db.Column(db.DateTime)
def __repr__(self):
return '<Category> %r>' % (self.courseName)
Upvotes: 9
Views: 3354
Reputation: 9440
It's because you've got a collision. The error is:
`sqlalchemy.exc.ArgumentError: Error creating backref 'category' on relationship 'Category.products': property of that name exists on mapper 'Mapper|Product|product'`
You can see that you've created a relationship within Category
to Product
which is two way, so you could do category.products
to list all the products associated with that category, or alternatively you could go product.category
which would give you the category for the selected product.
But you've already got a category
property in Product
. So just change it to be unique-- your Product
class should generally look like:
class Product(db.Model):
id = db.Column(db.Integer, primary_key = True)
category_id = db.Column(db.String(64), db.ForeignKey('category.id'))
courseName = db.Column(db.String(120), unique = True)
ip = db.Column(db.SmallInteger, default = WR_IP_YES)
duration = db.Column(db.Integer)
productRev = db.Column(db.String(64))
#use when database is updated?
releaseDate = db.Column(db.DateTime)
def __repr__(self):
return '<Category> %r>' % (self.courseName)
See how I've changed category
to category_id
so that the backref no longer collides with it.
Upvotes: 13