Home python Using the Relationship () function in SQLALCHEMY

Using the Relationship () function in SQLALCHEMY




Explain why SQLALCHEMY use the relalationship () function when creating classes of objects connected to the database tables, if the external keys can be specified when creating tables-tables using the function ForeignKey () when determining the column?
Or relationship () makes sense when using a declarative model when one class is determined for the table and the associated object?

Specify examples where it is shown as a class having fields defined through relationship () .

Answer 1, Authority 100%

Example from the author Pycon2013 ZZZeek

Create two tables User and Address .

class user (base):
  __TABLENAME__ = 'User'
  id = column (integer, primary_key = true)
  Name = Column (String)
  FullName = Column (String)
  Def __repr __ (Self):
    Return "& lt; User (% R,% R) & gt;" % (
        Self.name, self.fullname.
Class Address (Base):
  __Tablename__ = 'Address'
  id = column (integer, primary_key = true)
  email_address = column (String, NULLABLE = FALSE)
  user_id = column (Integer, ForeignKey ('user.id'))
  user = relationship ("user", backref = "addresses")

Using My_Address_obj.user We get the user object, and My_user_obj.Addresses will return the list of objects of all addresses linking to User . Thus, relalationship connects objects, and not just returns the value ID .

Example from Presentation:

# while the user has no "addresses"
jack = user (name = 'jack', fullname = 'jack bean')
jack.addresses # blank list
# Add addresses to him
jack.addresses = [
      Address (email_address='[email protected] '),
      Address (email_address='[email protected] '),
      Address (email_address='[email protected] '),

i.e. You operate with objects, not idids

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions