Django模型和SELECT连接两个或多个表?

时间:2011-02-10 09:17:04

标签: django django-models

如何使用Django模型使用两个(或更多)连接表进行选择?

例如:

class Album(models.Model):
    artist = models.ForeignKey(Musician)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

class Song(models.Model):
    album = models.ForeignKey(Album)
    name = models.CharField(max_length=100)
    num_stars = models.IntegerField()

SELECT * from album, song where (album.id = song.album_id) and (album.artist_id = X)

2 个答案:

答案 0 :(得分:13)

Django查询集希望返回模型实例的列表,这些列表并不完全映射到从连接到单个结果表的多个表中返回数据的SQL概念。

要实现您提供的SQL查询的效果,您可以执行以下操作之一:

1)如果您想通过歌曲迭代您的数据,您可以按艺术家ID限制您查询的歌曲,如下所示:

songs = Song.objects.filter(album__artist__id=123)
for song in songs:
    print song.name
    print song.album.name
    ... do what ever you need to do with song here ...

如果您担心性能问题,可以在查询集中添加select_related()

# the depth argument tells django to only follow foreign key relationships
# from Song one level deep
songs = Song.objects.select_related(depth=1).filter(album__artist__id=123)

for song in songs:
    # django has now already fetched the album data, so accessing it
    # from the song instance does not cause an additional database hit
    print song.album.name

2)如果你想通过专辑迭代你的数据,你可以这样做:

albums = Album.objects.filter(artist__id = 123)
for album in albums:
    for song in album.song_set.all():
        print song.name
        print album.name
        ... etc ...

答案 1 :(得分:0)

您可以执行raw sql query,但这可能不是您想要做的事情。解释您的模型的外观以及您想要实现的目标,并且可能django ORM足以执行查询。