[PYTHON] Difference between SQLAlchemy back_populates and backref and when neither is used

What is the difference between SQLAlchemy back_populates and backref? What happens if I don't write either of them? The story.

To write from the conclusion,

(1) When backref is used It automatically creates a two-way relationship.

(2) When back_populates is used You need to create a two-way relationship yourself.

(3) When neither back_populates nor backref is used Reversed fields are not automatically updated during a transaction.

It turns out that.

Let's look at a concrete example. Consider the Event model and Ticket model as examples. One Event has multiple Tickets, a One to Many relationship.

When using backref

class Event(Base):
	__tablename__ = 'event'
	id = Column(Integer, primary_key=True)
	title = Column(String(255))
	tickets = relationship("Ticket",backref="event")

class Ticket(Base):
	__tablename__ = 'ticket'
	id = Column(Integer,primary_key=True)
	title = Column(String(255))
	value = Column(Integer)
	event_id = Column(Integer,ForeignKey('event.id'))
event = Event(title="test")
ticket = Ticket(title="test_ticket",value=5000)
event.tickets = [ticket]

event.tickets #Ticket Objects
ticket.event #Event Object

When using back_populates

When using back_populates, it will not work unless you have a bidirectional relationship.

class Event(Base):
	__tablename__ = 'event'
	id = Column(Integer, primary_key=True)
	title = Column(String(255))
	tickets = relationship("Ticket",back_populates="event")

class Ticket(Base):
	__tablename__ = 'ticket'
	id = Column(Integer,primary_key=True)
	title = Column(String(255))
	value = Column(Integer)
	event_id = Column(Integer,ForeignKey('event.id'))
	event = relationship("Event",back_populates="tickets")
event = Event(title="test")
ticket = Ticket(title="test_ticket",value=5000)
event.tickets = [ticket]

event.tickets #Ticket Objects
ticket.event #Event Object

If neither is used

class Event(Base):
	__tablename__ = 'event'
	id = Column(Integer, primary_key=True)
	title = Column(String(255))
	tickets = relationship("Ticket")

class Ticket(Base):
	__tablename__ = 'ticket'
	id = Column(Integer,primary_key=True)
	title = Column(String(255))
	value = Column(Integer)
	event_id = Column(Integer,ForeignKey('event.id'))
	event = relationship("Event")
event = Event(title="test")
ticket = Ticket(title="test_ticket",value=5000)
event.tickets = [ticket]

event.tickets #Ticket Objects
ticket.event #None

In this case, ticket → event is None. In other words, it can be seen that the event is not associated with the ticket in the transaction. Of course, after the transaction ends (after inserting the event object), it is linked in both directions.

event = self.session.query(Event).filter(Event.id==1).one()
ticket = self.session.query(Ticket).filter(Ticket.id==1).one()

event.tickets #Ticket Objects
ticket.event #Event Object

Recommended Posts

Difference between SQLAlchemy back_populates and backref and when neither is used
Difference between SQLAlchemy filter () and filter_by ()
Difference between == and is in python
Difference between SQLAlchemy flush () and commit ()
What is the difference between `pip` and` conda`?
About the difference between "==" and "is" in python
What is the difference between Unix and Linux?
What is the difference between usleep, nanosleep and clock_nanosleep?
What is the difference between a symbolic link and a hard link?
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
Difference between np.array and np.arange
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Difference between Numpy randint and Random randint
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
[Introduction to Python] What is the difference between a list and a tuple?
difference between statements (statements) and expressions (expressions) in Python
[Django ORM] Difference between values () and only ()
Difference between PHP and Python finally and exit
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Difference between linear regression, Ridge regression and Lasso regression
[Python] Difference between class method and static method
Difference between docker-compose env_file and .env file
[Python Iroha] Difference between List and Tuple
[python] Difference between rand and randn output
speed difference between wsgi, Bottle and Flask
Difference between numpy.ndarray and list (dimension, size)
Difference between ls -l and cat command
Difference and compatibility verification between keras and tf.keras # 1