0

我有一个个人资料页面,其中列出了与用户相关的所有利益,以及与用户无关的所有利益。

我的问题是,它没有过滤用户,所以每个登录的人都会看起来像他们有他们没有的好处。

我的模型:

class PublishedManager(models.Manager):
    use_for_related_fields = True
    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(is_published=True)

class Benefit(models.Model):
    name = models.CharField(max_length=200)
    is_published = models.BooleanField(default=False)

    objects = models.Manager()
    published = PublishedManager()

class Profile(models.Model):
    user = models.OneToOneField(User)
    benefits = models.ManyToManyField(Benefit, blank=True, null=True, related_name="used_benefit")

我的观点:

class ProfileFrontpage(TemplateView):
    template_name = "profile/dashboard.html"

    def get_context_data(self, **kwargs):
            context = super(ProfileFrontpage, self).get_context_data(**kwargs)


            context['used_benefit_list'] = Benefit.published.filter(used_benefit__isnull=False)

            context['unused_benefits_list'] = Benefit.published.filter(used_benefit__isnull=True)


            return context

如何过滤与个人资料/用户相关的福利?

4

1 回答 1

1

You just need to add the corresponding filter criteria (This example shows filter on loggedin user )

user = self.request.user

benefits = Benefit.published.all()
used_benefit_list = benefits.filter(used_benefit__isnull=False, used_benefit__user = user)
unused_benefits_list = benefits.exclude(id__in = used_benefit_list)

context = {'used_benefit_list': used_benefit_list, 'unused_benefits_list': unused_benefits_list}
于 2013-11-12T15:31:43.303 回答