检查用户是否位于许多2个管理字段中



我有以下模型,其中有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 %}

尝试这样:

{% 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中找到了此解决方案:在模板中查看Manytomany字段中的值