python-3.x - Peewee ManyToMany 关系的中间表上的额外字段

标签 python-3.x orm peewee

我正在尝试通过 Peewee 3.2.2 中带有额外列的中间表建立多对多关系,如下所示:

ThroughDeferred = DeferredThroughModel()

class Playlist(BaseModel):
    ...
    movies = ManyToManyField(Movie, backref='playlists', through_model=ThroughDeferred)

class Movie(BaseModel):
    name = CharField(max_length=100)

class PlaylistMovie(BaseModel):
    playlist = ForeignKeyField(column_name='playlist_id', field='id', model=Playlist)
    movie = ForeignKeyField(column_name='movie_id', field='id', model=Movie)
    position = PositiveSmallIntegerField(default=1)

    class Meta:
        table_name = 'playlist_movie_relation'

ThroughDeferred.set_model(PlaylistMovie)

但是,在查询时我得到的只是没有位置的相关电影数据列表。

list(playlist.movies.dicts()) 
> [{name: 'blah', id: 3}, ...]

如何获取 playlist.movi​​es 中的位置数据?

最佳答案

这应该有效:

query = (Movie
         .select(Movie, PlaylistMovie.position)
         .join(PlaylistMovie)
         .where(PlaylistMovie.playlist == playlist)
         .order_by(PlaylistMovie.position))

for movie in query:
    print(movie.name, movie.playlistmovie.position)

关于python-3.x - Peewee ManyToMany 关系的中间表上的额外字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831238/

相关文章:

mysql - 使用 peewee 连接 mysql 以及访问表的一些问题

python - 如何以渐进方式生成没有值的组合

python - 配置 Pycharm 以运行 Pyinstaller

java - 创建实体和非实体对象之间的关系

python - 如何从批量插入 Peewee 中获取 ID?

python - 如何在 peewee 元类中使用默认排序

python - 无法在 matplotlib 中使用自定义字体

python - 如何在 python 中创建悬挂指针(在堆栈或堆中)

java - 如何将主键也用作 JPA 和 Hibernate 的外键引用?

database - ORM 是否适用于非 CRUD 数据库?