Jul*_*pov 6 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)
Run Code Online (Sandbox Code Playgroud)
zlo*_*ady 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 ...
Run Code Online (Sandbox Code Playgroud)
如果您担心性能,可以将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
Run Code Online (Sandbox Code Playgroud)
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 ...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10869 次 |
最近记录: |