【问题标题】:Django Using attribute of queryset objectDjango 使用查询集对象的属性
【发布时间】:2021-10-26 13:23:39
【问题描述】:

我为我的页面创建了 cmets/messages 区域。我也为他们创建了like按钮。当用户进入页面时,我想显示他默认的喜欢按钮(喜欢或不喜欢)。 如果用户在点赞列表中,我想显示他的不同,但如果它不在列表中,也就是说,如果它还没有被点赞,我想显示点赞按钮。强>

观看次数:

def detail_post(request,_detail):
   postDetail =  UserPosts.objects.get(pk = _detail) #This is post
   messages = UserMessages.objects.all().filter(post_id =postDetail.id) #This is comment of post

   # I tried this but iit is not works
   for x in messages:
      total = x.like_message.all()
      print(total)    
   context= {
    "detail":postDetail,
    "messages":messages,
   }

模板:

{% for message in messages %}
     {% if message.username_id == request.user.id %}
           <button class="btn btn-primary btn-sm" title="You can't like your message" disabled >Like</button>
     {% else %}
          <button class="btn btn-primary btn-sm text-white btn-like {{ message.id }} " type="submit" name="usermessages_id"
          value="{{ message.id }}" id="{{ message.id }}"> Like </button>
      {% endif %}
{% endfor %}

这是我在 Views 文件中编写的 for 循环的输出:

  <QuerySet [<User: vahandag>]>
  <QuerySet [<User: vahandag>, <User: GladyaTH0R>, <User: user2>, <User: user3>, <User: vahandag1905>]>
  <QuerySet []>
  <QuerySet []>
  <QuerySet [<User: vahandag1905>]>
  <QuerySet [<User: vahandag1905>]>
  <QuerySet [<User: vahandag>]>

我想要这个:

{% if message.username in message.like_message.all() %}
      <button> Unlike </button>
{% else %}
      <button> Like </button>
{% endif %}

有人有想法吗?

【问题讨论】:

    标签: python html django django-views django-templates


    【解决方案1】:

    试试这个

    {% if message.username in message.like_message.all %}
          <button> Unlike </button>
    {% else %}
          <button> Like </button>
    {% endif %}
    

    您不必在模板引擎中以 '()' 结束方法

    【讨论】:

      【解决方案2】:

      试试这个

      def detail_post(request,_detail):
          postDetail =  UserPosts.objects.get(pk = _detail) 
          messages = UserMessages.objects.all().filter(post_id=postDetail.id).values() 
          #This is comment of post
      
          # I tried this but iit is not works
          for x in messages:
              total = x.like_message.all()
              print(total)    
              context= {
                 "detail":postDetail,
                 "messages":messages,
                 }
      

      【讨论】:

      • 谢谢先生的帮助。上面的答案对我有用
      • filter 返回一个新的 QuerySet,其中包含与给定查找参数匹配的对象。 values 返回一个返回字典而不是模型实例的 QuerySet。
      猜你喜欢
      • 2011-03-04
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2021-05-16
      • 2013-12-11
      相关资源
      最近更新 更多