While undertaking a coding project earlier this week, all hell broke loose, not-so-literally. I was creating a User model, to store some information of registered users to the database, a Product model to store various details about the product and separate brand and categories models to data on brands and categories related to the product.
Upon setting up the models, I migrated the changes and upgraded the db’s version. A successful migration and upgrade process of course guaranteed that my models were all set and that there was absolutely nothing to worry about, or so I thought.
When firing up my application to perform random tests on its functionality, I ran into this error:
What followed was a moment of panic and a deep sense of dread, where could I have possibly gone wrong? Of course I now know better but that wasn’t the case then.
Upon further assessment on what could have triggered the issue, I noticed a rookie mistake but it was all-in-all quite an eye-opener! Let’s get to the crux of the matter:
Notice anything disturbing? Of course there exists a database relationship between brand-product and category-brand. Sqlalchemy allows us to express this relationship by use of db.relationship(). In a one-to-many relationship, db.relationship() is added on the one side and it takes the following as arguments in this case:
- The model which is on the many side(don’t forget to capitalize the first character of this model)
- The backref argument expresses how this relationship will be referenced. For example, if we wanted to find out what category a particular product belongs to, we’d simply reference product.category. Note that the db.relationship(…) is not a column in the table it has been listed in but it’s just a way that sqlalchemy allows us to create and reference relationships.
- The lazy argument that implies how the query will be executed
The error was triggered by the fact that I used the same backref name on two separate occasions i.e in our example, the backref name ‘category’ was used twice. A simple name-change on either of the backrefs solves our problem and leaves our code error-free, at least for now.
Happy coding folks!