如何按用户订阅显示主题类别的主题

时间:2018-12-28 10:07:45

标签: python django django-views

我是Django Python框架的新手。 我有主题模型,子渠道模型,子渠道订阅模型。

我想根据用户订阅的内容显示主题。 例如,如果用户仅订阅了物理类别,则该用户应仅看到物理主题

Python 3和Django 2

public class ConfigureCookieAuthenticationOptions : IPostConfigureOptions<CookieAuthenticationOptions>
{
    private readonly IMemoryCache _memoryCache;

    public ConfigureCookieAuthenticationOptions(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    public void PostConfigure(string name, CookieAuthenticationOptions options)
    {           
        options.SessionStore = new InMemoryCacheTicketStore(_memoryCache);          
    }
}

我在下面显示了用户订阅的Views.py代码

class SubChannelSubscription(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscriptions',
                             verbose_name='Subscriber', default=True)
    category = models.ForeignKey(SubChannel, related_name='Topic+', on_delete=models.CASCADE,
                                   verbose_name='SubChannel', default=True)

    def __str__(self):
        return '%(user)s\'s subscription to "%(category)s"' % {'user': self.user, 'category': self.category}

    class Meta(object):
        verbose_name = 'Subscription to SubChannel'
        verbose_name_plural = 'Subscriptions to SubChannel'


class Topic(models.Model):
    by = models.ForeignKey(User, on_delete=models.CASCADE, default=True)
    subject = models.CharField(max_length=150, unique=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(SubChannel, on_delete=models.CASCADE, null=True, default=True, related_name='topics')
    file = RichTextUploadingField(blank=True, null=True)


    def __str__(self):
        return self.subject

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

我的urls.py

class SubChannelSubscriptionView(ListView):
    template_name = 'subscription.html'
    model = Topic

    def get_queryset(self):
        self.user = get_object_or_404(User, pk=self.kwargs['pk'])
        return SubChannelSubscription.objects.filter(user=self.user)

    def get_context_data(self, **kwargs):
        context = super(SubChannelSubscriptionView, self).get_context_data(**kwargs)
        context['topics'] = self.user
        context['top'] = Topic.objects.filter(category=1)
        return context

1 个答案:

答案 0 :(得分:0)

对于您而言,它看起来像:

Topic.objects.filter(category__Topic+__user=self.user)

但是我建议将related_name字段中的category重命名为更好的名称,例如:

class SubChannelSubscription(models.Model):
    ....
    category = models.ForeignKey(
        SubChannel, 
        related_name='subchannel_subs', 
        on_delete=models.CASCADE,
        verbose_name='SubChannel', 
        default=True
    )

如果进行了更改,查询将如下所示:

Topic.objects.filter(category__subchannel_subs__user=self.user)

您可以做到

context['top'] = Topic.objects.filter(category__subchannel_subs__user=self.user)