简体   繁体   English

模板中的Django过滤器查询集

[英]Django filter queryset in template

I'm still studying in school and still new in Python language & Django framework and I'm trying doing projects to learn the best practice for it. 我仍在学校学习,并且仍然是Python语言和Django框架的新手,并且我正在尝试做一些项目来学习最佳实践。

Right now I'm building a project like following : 现在,我正在构建一个如下项目:

  • Topics Model => which is user can write a new topic 主题模型=>这是用户可以写一个新主题
  • Replies Model => which is user can write a new reply for a specific topic 回复模型=>,用户可以针对特定主题写新的回复
  • Likes Model => which is user can vote up or down for a topic or reply 喜欢模型=>,表示用户可以投票赞成或反对某个主题或回复

it's a little bit close from stackoverflow site . 它离stackoverflow站点有点近。

Models.py 型号

class Topic(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.CharField(max_length=400)
like = models.IntegerField(default=0)
dislike = models.IntegerField(default=0)
image = models.FileField(blank=True, null=True)
created_date = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.title[0:51]



class Reply(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
reply = models.TextField()
created_date = models.DateTimeField(auto_now=True)

def likes(self):
    return Likes.objects.filter(reply=self, reply_flag=1).count()
    likes.short_description = 'likes'

def dislikes(self):
    return Likes.objects.filter(reply=self, reply_flag=-1).count()
    dislikes.short_description = 'dislikes'

def __str__(self):
    return self.reply



class Likes(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
reply = models.ForeignKey(Reply, on_delete=models.CASCADE)
reply_flag = models.CharField(max_length=5, choices=(
('0', 'No'), ('1', 'Positive'), ('-1', 'Negative')))  # 1 = vote up , -1 vote down

Views.py Views.py

# get all topics 
def Topics(request):
topics = models.Topic.objects.all()
return render(request, 'Topics.html', {'topics': topics})



# get detail of specific topic
def TopicDetails(request, topic_id):
topic = get_object_or_404(models.Topic, pk=topic_id)
return render(request, 'Topic_Details.html', {'topic': topic, 'Likse': models.Likes.objects.all})

Templates: 范本:

topics.html : topic.html:

 {% for topic in topics %}

   {% if topic.image}
      <img src="{{topic.image.url}}"
   {% endif %}
   title : {{ topic.title }}
   by : {{ topic.user }}
   total agree : {{ topic.like }}
   total not agree : {{ topic.dislike }}

{% endfor %}

topic.html : topic.html:

 topic title : {{ topic.title }}

 {% for reply in topic.reply_set.all %}

   reply : {{ topic.reply }}
   by : {{ reply.user }}
   total agree : {% for like in reply.lieks_set.all %} {% if like.reply == reply and like.reply_flag == '1' %} <!-- should be total of vote up --> {% endif %} {%endfor %}
   total not agree : {% for like in reply.lieks_set.all %} {% if like.reply == reply and like.reply_flag == '-1' %} <!-- should be total of vote down --> {% endif %} {%endfor %}

{% endfor %}

I faced an issue with filter likes based on reply, user and reply flag (vote up, vote down) in topic.html, I have two questions : 我在topic.html中遇到基于回复,用户和回复标志(投票,否决)的喜欢过滤条件的问题,我有两个问题:

  • As my knowledge and as I read after search I couldn't filter data in template, So how could I show the filtered data in template based on reply, user and reply flag (vote up, vote down) ? 据我所知,以及在搜索后的阅读中,我无法过滤模板中的数据,那么如何根据回复,用户和回复标志(投票,否决)在模板中显示已过滤的数据?
  • Is structure of app is correct ? 应用程序的结构是否正确?

First of all, you should definitely make use of generic views (like DetailView or TemplateView ). 首先,您一定要使用通用视图(例如DetailViewTemplateView )。 You have couple of options on how to include proper information, decide which is simpler for you: 对于如何包括适当的信息,您有几种选择,可以确定哪种更简单:

  1. Override a get_context of a generic view (and include aggregates in a template variable) 覆盖通用视图的get_context (并将聚合包括在模板变量中)
  2. Override get_queryset of a view (inluding aggregates in a query) 倍率get_queryset视图的(在查询inluding聚集体)
  3. Create a custom model manager and include appropriate aggregates in a queryset. 创建一个自定义模型管理器,并在查询集中包含适当的聚合。

See aggregate and annotate for more information on how to count or sum dependent models. 有关如何计算或求和依赖模型的更多信息,请参见aggregateannotate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM