检查用户是否在 Many2Many 字段中

Check if User is in Many2Many field

我有以下带有 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})

现在,当登录用户已经对该出版物感兴趣时,我尝试在模板中生成 "i am already interested":

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 %}

这样试试:

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

这看起来是个不错的解决方案:

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

中找到了这个解决方案