查询集按另一个查询集中的变量过滤

时间:2021-02-18 19:37:29

标签: python django django-views

我正在尝试通过另一个尚未设置的查询集中的变量过滤查询集。我知道这听起来令人困惑,所以让我向您展示。

视图.py

from pyspark.sql import functions as F, Window

df = df.withColumn('idx',F.row_number().over(Window.orderBy('age')))
df.show()
+----+---+---+---+---+---+---+
| vin|age|var|rim|cap|cur|idx|
+----+---+---+---+---+---+---+
| tom| 10| 54| 87| 23| 90|  1|
|juli| 14| 87|  9| 43| 21|  2|
|nick| 15| 63| 23| 11| 65|  3|
+----+---+---+---+---+---+---+

df2 = df.union(
    spark.createDataFrame([data_1], schema).withColumn(
       'idx',
       F.row_number().over(Window.orderBy('age')) + F.lit(df.select(F.max('idx')).head()[0])
    )
)

df2.show()
+----+---+---+---+---+---+---+
| vin|age|var|rim|cap|cur|idx|
+----+---+---+---+---+---+---+
| tom| 10| 54| 87| 23| 90|  1|
|juli| 14| 87|  9| 43| 21|  2|
|nick| 15| 63| 23| 11| 65|  3|
| sam| 60| 45| 34| 12| 67|  4|
+----+---+---+---+---+---+---+

发布模型

def ViewThreadView(request, thread):
    posts = Post.objects.filter(post_thread=thread)
    thread = Thread.objects.get(pk=thread)
    form_class = QuickReplyForm
    thread_name = thread.name

  
    return render(request, 'thread/viewthread.html',
                  {'thread': thread, 'posts': posts, 'thread_name': thread_name})

User 模型是标准的 Django 模型

截至目前,如果我想访问模板中的帖子作者,我会这样做

class Post(models.Model):
    post_body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.author)

我的问题是,如何访问 post.author 的表。因此,如果我想过滤该作者拥有的帖子数量,我想执行类似 {% for post in posts %} post.author {% endfor %} 的操作。但这在视图中不起作用,因为“posts”是一个查询集而不是一个值。我该怎么做?

1 个答案:

答案 0 :(得分:2)

在您的模板中,您可以使用 post_set 访问您的相关对象:

{% for post in posts %}
    {{ post.author.post_set.count }}
{% endfor %}

如果您需要更多帖子总数,您是要过滤相关对象还是其他内容。您始终可以为您的模型编写自定义方法。见Model methods

例如:

from django.utils.functional import cached_property


class Post(models.Model):
    post_body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.author)

    @cached_property
    def count_by_author_and_thread(self):
        return self.author.post_set.filter(post_thread=self.post_thread).count()

然后在您的模板中简单使用:

{% for post in posts %}
    {{ post.count_by_author_and_thread }}
{% endfor %}