我试图从ManyToManyField
获取数据,但发现运气不好。你能帮帮我吗?
这是我的Song App
模型。
class Artist(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value automatically generated from name. Must be unique.")
class Album(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value automatically generated from name. Must be unique.")
path = models.CharField(max_length=100,null=True, blank=True)
language = models.ForeignKey(Category)
albumid = models.CharField(max_length=100)
class Song(models.Model):
title = models.CharField(max_length=100)
artist = models.ManyToManyField(Artist)
music = models.ForeignKey(Music)
album = models.ForeignKey(Album)
这是我的看法。我想用标题打印艺术家。 Titles
工作正常。但不是Artist
def movie_details(request,slug):
movies = get_object_or_404(Movie,slug=slug)
# calculating wikipedia directory structer for images
#image_name = movies.image
name = movies.title
album_name = Album.objects.get(name__exact=name)
album_id = album_name.id
song_list = Song.objects.filter(album=album_id)
#image_path = generateWikiImage(image_name)
#
return render_to_response('base_movies.html',locals(),
context_instance=RequestContext(request)
)
我试过像这样的模板。 {{song_list.artist}}
并收到此消息<django.db.models.fields.related.ManyRelatedManager object at 0x024CBED0>
感谢
答案 0 :(得分:8)
ManyRelatedManager
是处理ManyToMany关系的对象。要获取您要查找的对象列表,您需要使用其all()
方法。
在这种情况下,您将使用{{song_list.artist.all}}
,它将为您提供一个QuerySet,然后您可以在模板中进行迭代。
答案 1 :(得分:2)
ManyToManyField
包含查询集,因此您不能只在模板中输出它。你应该迭代它。
像这样(song
是一些Song
实例)
<ul>
{% for artist in song.artist.all %}
<li>{{ artist.name }}</li>
{% endfor %}
</ul>