查询通过外键链接的 Django 模型以获得完整的查询集,计算喜欢的帖子

问题描述 投票:0回答:1

这是一个 CS50 Pset - 网络 - 我正在努力解决这个问题,除了这一点已经完成了

我想我已经把自己困在了一个角落里,我有4个不同的模型,其中3个与这个问题相关,用户,帖子和LikeMatrix。 LikeMatrix 对用户模型(用户)和帖子模型(帖子)使用外键,它是一个记录用户喜欢什么帖子的矩阵,因为我无法让我最初的想法与用户和帖子之间的多对多链接一起工作帖子模型。 (如果我重来一次,我会采取不同的做法)。我的 Js 正在工作,我的 API 正在工作,除了最后一块拼图之外,其他所有东西都在工作,以计算 LikeMatrix 模型中每个帖子的点赞数,然后将其发送到 index.html

我在views.py中运行一个查询,从Posts中提取数据并将其在模板/查询集中发送到index.html,请参阅下面的屏幕截图了解屏幕上的样子。我确信有很多更专业的方法来做我正在做的事情,但我一边学习一边独立做,这已经花了我几周的时间......关于让这个问题看起来更好的任何建议当我粘贴它时,我将不胜感激。

models.py

class User(AbstractUser):    
    pass


class Posts(models.Model):   #notes for future, use singular in naming for admin reasons.
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author")
    content = models.CharField(max_length=280)  #twitter style
    timestamp = models.DateTimeField(auto_now_add=True) #django docs - may be incorrect options    

    def __str__(self):
        return f' number {self.id} post, Posted by {self.user} '

class LikeMatrix(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="liker")
    post = models.ForeignKey(Posts, on_delete=models.CASCADE, related_name="post")

    def __str__(self):
        return f"{self.user} likes {self.post} post"

索引.html

它会在下面进行迭代并填充index.html中的帖子(抱歉,其中有一些评论让我跟踪我所在的位置)。这一切都按照屏幕截图填充,除了镜头中的喜欢数,它只是我在编程时使用的静态占位符。我需要做的是能够计算每个帖子的点赞数,我相信它可以计算 LikesMatrix 中每个帖子的用户数。

{% for post in pagePosts %}

            <div class="col-12">
                <div class="row">
                    <!--<h3 class="username" href="{% url 'profile' user_id=user.id %}">   @{{post.user}}</h3>-->
                    <h3 ><a class="username" href="{% url 'profile' user_id=post.user.id %}">@{{post.user }}</a></h3>  <!-- font size to be sorted -->
                    <h3 class="edit"> Edit</h3>
                    <h3 class="content">  {{post.id}}</h3>

                    <h3 class="content" id="content_{{post.id}}"> {{post.content}}</h3>
                    <h3 class="date"> {{post.timestamp}}</h3>

                    <div>
                    {% if user == post.user %}
                      <h5 class="likes"> <label id="likes">&#128151  <label id="postLikes">{{post.likes}}</h5>
                      <!--this is just a red heart and a number - no onclick here;>-->

                    {% elif post.id in likedPostsUser %}
                    <div>
                      <h5 class="likes2" id="clickLikes_{{post.id}}" onclick="clickLikesRoutine({{post.id}}, 'True')">💗</h5><label id="likesNum">{{post.likes}}</label>

                    </div>
                    {% else %}
                      <h5 class="likes2" id="clickLikes_{{post.id}}" onclick="clickLikesRoutine({{post.id}}, 'True')">🤍</h5><label id="likesNum">{{post.likes}}</label>


                    {% endif %}
                    </div>


                    <div>
                        <!--Edit Modal Bootstrap>-->
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#edit_text_modal_{{ post.id }}">
                            Edit
                          </button>



我尝试过 Django Count()、python count()、annotate、select_lated,我花了几个小时尝试练习如何提取和分组这些数据。我可以获得帖子 的整数 id 查询集,它告诉我帖子 11 已被点赞 3 次,1、13、14 均已被点赞一次,我还可以获得已点赞帖子的完整列表以及谁通过标题和用户名喜欢它们,但无法理解下面的内容。我不需要完整的解决方案,但需要一些指导来帮助我理解该过程。心形下方的数字 1 只是一个静态占位符,当我使其正常运行时,将替换为该数据,谢谢

this gets me the queryset above
likedPosts = LikeMatrix.objects.all().values_list('post_id', flat=True) 


this is my all post query I send to index.html
allPosts = Posts.objects.all().order_by("id").reverse() 



I have now made some progress using len() and .filter() to get back the number of times a posts id is in a queryset, my current thoughts are now to use distinct() to filter the existing queryset and then loop the remainer values through the equation below and append to a new list, im sure there are easier ways but Im working on it, thanks

current_vote = len(LikeMatrix.objects.select_for_update().filter(post='14'))
    print(current_vote)

django django-queryset cs50
1个回答
0
投票

如果您尝试按总喜欢对帖子进行分组,并假设您将查询集转换为简单列表,如 [1, 11, 11, 11, 13, 14] 的示例中所示。您只需执行以下操作即可:

sample = [1,11,11,11,13,14]
grouped = {} # key will be the post id and the value will be total occurences (likes)
for post_id in set(sample): # set will convert the list with duplicate to unique values.
  grouped[str(post_id)] = sample.count(post_id)

您最终将得到以下结果:

{'1': 1, '11':3, ...}

© www.soinside.com 2019 - 2024. All rights reserved.