我有一个个人资料页面,其中列出了用户的所有连接好处,以及与用户无关的所有好处。
我的问题是,它不是对用户进行过滤,因此每个登录的人看起来都会有他们没有的好处。
我的模特:
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
如何过滤与个人资料/用户相关的福利?
答案 0 :(得分:1)
您只需添加相应的过滤条件(此示例显示已登录用户的过滤器)
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}