Вопрос

I have a model User and a model Thing. A User can own zero or more Things. A Thing may be owned by zero or more Users. Ordinarily I would add in a third table Thing_Ownership linking Users to Things but I would like to take advantage of SQLAlchemy's backref feature so that if I had a User instance george I could call george.inventory to get a list of Things that belong to george.

What is the best way to go about this, or should I just add a third model and implement User.inventory as a search through a third Thing_Ownership model for relevant relationships?

Это было полезно?

Решение

Check out SQLAlchemy's documentation on Many to Many relationships - it should do exactly what you're looking for.

So if you have models for User and Thing, you can set up a secondary parameter in your relationship:

from sqlalchemy import Table, Integer, Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

association_table = Table('association', Base.metadata,
    Column('user_id', Integer, ForeignKey('user.id')),
    Column('thing_id', Integer, ForeignKey('thing.id'))
)

class User(Base):
    __tablename__ = 'user'
    # Whatever you need in this model
    inventory = relationship('Thing', secondary = association_table, backref = 'users')

class Thing(Base):
    __tablename__ = 'thing'
    # Whatever you need in this model

You can then access a list of Things belonging to a User instantiated as george by calling george.inventory.

Hope this helps.

EDIT: Reread your question and saw you wanted to use backref - added code to do that.
EDIT 2: Left out a really important part.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top