检查用户是否在Many2Many字段中

时间:2017-09-13 12:45:57

标签: django m2m

我有一个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})

现在我尝试制作一个"我已经感兴趣了#34;当登录用户已对该出版物感兴趣时,在模板中:

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

2 个答案:

答案 0 :(得分:1)

试试这样:

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

答案 1 :(得分:1)

这似乎是一个很好的解决方案:

<强> 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

中找到此解决方案