外键查找 - 使用Django通用列表视图的slug URL

时间:2014-07-17 08:22:48

标签: django python-2.7

我一直在这里搜索并阅读文档并在python中进行实验,但我无法找到解决我特定问题的方法。我做了Django教程,但我仍然对如何在开始使用外键时通过django中的URL传递内容感到困惑,我确信它非常简单。我是一个新的django用户,这是我的第一篇文章。我有模型播放列表和PlaylistEntry与用户和视频(未发布)的混合关系。我试图显示一个使用一段播放列表标题的详细视图来提取播放列表中的条目。例如。在python中,我可以做到

    entries = PlaylistEntry.objects.filter(playlist__slug='django')

返回播放列表中的所有条目' Django'正确。

以下是我的模特......

class Playlist(models.Model):
    class Meta:
        verbose_name_plural = 'playliztz'


    title = models.CharField(blank=True, 
        help_text=u'Title of playlist',
        max_length=64,
        )

    user = models.ForeignKey('userprofile.UserProfile', 
        blank=False,
        help_text=u'owns this playlist',
        null=False, )


    slug = models.SlugField(u'slug',
        max_length=160,
        blank=True,
        editable=False
        )

    created = models.DateTimeField(editable=False)
    modified = models.DateTimeField(editable=False)


    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('playlist-detail', kwargs={'pk': self.pk})

    def save(self):
        self.slug = slugify(self.title)
        if not self.id:
            self.created = datetime.datetime.today()
        self.modified = datetime.datetime.today()
        super(Playlist,self).save() 


class PlaylistEntry(models.Model):
    class Meta:
        verbose_name_plural = "playlist entries"

    video = models.ForeignKey('video.Video',
        blank=True,
        default=None,
        help_text=u'the video title',
        null=True, )

    playlist = models.ForeignKey('Playlist', 
        blank=True,
        default=None,
        help_text=u'Belongs to this playlist',
        null=True,)

    def __unicode__(self):
        return self.video.video_title

我的网址看起来像这样......

    url(r'^playlist/$', PlaylistList.as_view(), name='user_playlists'),
    url(r'^playlist/(?P<slug>[0-9A-Za-z-_.//]+)/$', PlaylistDetail.as_view(), name='playlist_entries'),

我的Views.py看起来像这样......

    class PlaylistList(LoggedInMixin, ListView): # shows a list of playlists
        template_name = 'userprofile/playlist_list.html'
        model = Playlist
        context_object_name = 'playlist_list'

        def get_queryset(self):
            """Return currently users playlists."""
            return Playlist.objects.filter(user__user=self.request.user)

        def get_context_data(self, **kwargs):
            context = super(PlaylistList, self).get_context_data(**kwargs)
            if not self.get_queryset():
                context['error'] = "You don't have any playlists yet."
                return context 
            else:
                return context

    class PlaylistDetail(LoggedInMixin, DetailView):
        model = PlaylistEntry
        template_name = 'userprofile/playlist_detail.html'

        def get_queryset(self):
            self.current_playlist = get_object_or_404(Playlist, slug=self.kwargs['slug'])

            # CHECK - Prints out correct entries for playlist in slugfield (current_playlist)
            self.entries = PlaylistEntry.objects.filter(playlist__title=self.current_playlist.title)
            print self.entries 

            # Should expect to return the same queryset?
            return PlaylistEntry.objects.filter(playlist__title=self.current_playlist.title)


        def get_context_data(self, **kwargs):
            context = super(PlaylistEntry, self).get_context_data(**kwargs)
            context['entries'] = PlaylistEntry.objects.all()
            return context

self.entries在Check位中打印此播放列表的正确条目。

在我的播放列表模板中,我使用的是发送playlist.slug的链接 - 该网址看起来像这样/ user / playlist / this-specific-playlist-slug。

错误是......

    Cannot resolve keyword u'slug' into field. Choices are: id, playlist, video

1 个答案:

答案 0 :(得分:0)

你使事情变得比他们需要的要复杂得多。

您的详细信息视图的模型应该仍然是播放列表,而不是PlaylistEntry。你获得该错误的原因是slug在播放列表模型上,但你已经告诉视图过滤PlaylistEntry。

您真正想要的是将slug标识的单个播放列表传递到模板中。从那里,您可以通过反向关系轻松地遍历与该播放列表关联的详细对象。

因此,更改该模型设置,并从详细信息视图中删除get_context_dataget_queryset:您不需要它们。然后在模板中你可以做到:

{% for entry in playlist.playlistentry_set.all %}