【问题标题】:Check if User is in Many2Many field检查用户是否在 Many2Many 字段中
【发布时间】:2018-02-22 04:36:38
【问题描述】:

我有以下模型,其中包含 m2m 字段,登录的用户可以对出版物表现出兴趣:

models.py

from django.db import models

class Publication:
  title = models.CharField(max_lenth=512)
  users_interested = models.ManyToManyField(User)

views.py

from django.shortcuts import render
from django.views import View
from .models import Publication

class listPublicationView(View):
  def get(self, request, *args, **kwargs):

    publications = Publication.objects.all()

    return render(request, "base.html", {'publications': publications})

现在,当登录用户已经对出版物感兴趣时,我尝试在模板中生成“我已经感兴趣”:

base.html

{% for publication in publications %}

  {{publication.title}}

  {% if currently logged in User is interested in publication (check users_interested) %}
      i am already interested
  {% endif %}

{% endfor %}

我在想这样的事情:

{% if user.id in publication.users_interested__id %}

【问题讨论】:

  • 您必须在视图中加载您想要的信息。该模板不是用来生成任何东西的(除了 html、ofc)。在您的情况下,可能是某种形式的prefetch_related()annotate()

标签: django m2m


【解决方案1】:

试试这样:

{% if request.user in publication.users_interested.all %}
  • request.user 属性保存当前登录用户
  • 然后您将in 运算符与publications.users_interested.all() 一起使用(请注意,模板中.all() 上没有括号

【讨论】:

  • 在他的模板循环中,如果他有 1000 个出版物,他的页面会突然用 1001 个查询压垮数据库。
  • 这行得通——但我真的会有几百个出版物
【解决方案2】:

这似乎是一个不错的解决方案:

models.py

from django.db import models

class Publication:
  title = models.CharField(max_lenth=512)

  #added a reverse accessor
  users_interested = models.ManyToManyField(User, related_name='users_interested')

view.py

from django.shortcuts import render
from django.views import View
from .models import Publication

class listPublicationView(View):
  def get(self, request, *args, **kwargs):

    publications = Publication.objects.all()

    # create a set of group IDs that this user is a part of
    current_user = request.user
    user_publication_set = set(current_user.users_interested.values_list('id', flat=True))

    #pass set to template
    return render(request, "base.html", {'publications': publications, 'user_publication_set': user_publication_set})

base.html

{% for publication in publications %}

  {{publication.title}}

  {% if publication.id in user_publication_set %}
      i am already interested
  {% endif %}

{% endfor %}

Django: check for value in ManyToMany field in template找到这个解决方案

【讨论】:

  • 这确实是一个更好的解决方案。关键是始终让视图确定应该加载哪些数据,以便它可以控制逻辑。这正是你所做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
相关资源
最近更新 更多