我还在学校学习,还有Python语言和新学习Django框架和我正在尝试做项目来学习它的最佳实践。
现在我正在构建如下项目:
它与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
# 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})
模板:
topics.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 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 %}
我在topic.html中遇到了基于回复,用户和回复标记(投票,投票结果)的过滤器喜欢的问题, 我有两个问题:
答案 0 :(得分:0)
首先,您绝对应该使用通用视图(例如DetailView
或TemplateView
)。关于如何包含适当的信息,你有几个选择,决定哪个更简单:
get_context
(并在模板变量中包含聚合)get_queryset
(包括查询中的聚合)有关如何对依赖模型进行计数或求和的详细信息,请参阅aggregate
和annotate
。