Can I use SQLAlchemy relationships in ORM event callbacks? Always get None

2024/10/4 21:28:59

I have a User model that resembles the following:

class User(db.Model):id = db.Column(db.BigInteger, primary_key=True)account_id = db.Column(db.BigInteger, db.ForeignKey('account.id'))account = db.relationship('Account',backref=db.backref('ref_users', cascade='delete'))...def after_user_write(mapper, connection, target):target.account.invalidate_cache()event.listen(User, 'after_insert', after_user_write)
event.listen(User, 'after_update', after_user_write)
event.listen(User, 'after_delete', after_user_write)

Upon insert after_user_write is being called, but target.account is None (which causes an error) when I expect it to be an Account model. target.account_id is set correctly, it just seems like the relationship reference isn't working as I'd expect.

Any ideas on what's causing this?

Answer

The relationship doesn't get set by SQLAlchemy automatically when manually creating objects. If you want to access account in the event callback, set it when you create the User instance:

a1 = Account()
u1 = User(account_id=a1.id)
db.session.add(u1)
db.session.commit()assert u1.account is Nonea2 = Account()
# Here: set the account object, instead of the id
u2 = User(account=a2)
db.session.add(u2)
db.session.commit()assert u2.account == a2
assert u2.account_id == a2.id
https://en.xdnf.cn/q/70565.html

Related Q&A

Elegant way to transform a list of dict into a dict of dicts

I have a list of dictionaries like in this example:listofdict = [{name: Foo, two: Baz, one: Bar}, {name: FooFoo, two: BazBaz, one: BarBar}]I know that name exists in each dictionary (as well as the oth…

sharpen image to detect edges/lines in a stamped X object on paper

Im using python & opencv. My goal is to detect "X" shaped pieces in an image taken with a raspberry pi camera. The project is that we have pre-printed tic-tac-toe boards, and must image t…

How to change the color of lines within a subplot?

My goal is to create a time series plot for each column in my data with their corresponding rolling mean. Id like the color of the lines across subplots to be different. For example, for gym and rollin…

Cythons calculations are incorrect

I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:from __future__ import division pi = 0 l = 1 x = True while True:if x:pi…

Python: NLTK and TextBlob in french

Im using NLTK and TextBlob to find nouns and noun phrases in a text:from textblob import TextBlob import nltkblob = TextBlob(text) print(blob.noun_phrases) tokenized = nltk.word_tokenize(text) nouns =…

How can I run a script as part of a Travis CI build?

As part of a Python package I have a script myscript.py at the root of my project and setup(scripts=[myscript.py], ...) in my setup.py.Is there an entry I can provide to my .travis.yml that will run my…

Writing nested schema to BigQuery from Dataflow (Python)

I have a Dataflow job to write to BigQuery. It works well for non-nested schema, however fails for the nested schema.Here is my Dataflow pipeline:pipeline_options = PipelineOptions()p = beam.Pipeline(o…

Python decorators on class members fail when decorator mechanism is a class

When creating decorators for use on class methods, Im having trouble when the decorator mechanism is a class rather than a function/closure. When the class form is used, my decorator doesnt get treated…

Why does comparison of a numpy array with a list consume so much memory?

This bit stung me recently. I solved it by removing all comparisons of numpy arrays with lists from the code. But why does the garbage collector miss to collect it?Run this and watch it eat your memor…

StringIO portability between python2 and python3 when capturing stdout

I have written a python package which I have managed to make fully compatible with both python 2.7 and python 3.4, with one exception that is stumping me so far. The package includes a command line scr…