好的,所以我有一个测试博客系统来练习我的django技能。我有两个应用程序,一个叫做文章,一个叫做喜欢,它们是:
文章模型:
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField()
pub_date = models.DateTimeField('Date Published',auto_now = True)
def __str__(self):
return self.title
以下是喜欢的模特:
from django.db import models
from apps.article.models import Article
# Create your models here.
class Like(models.Model):
article_id = models.ForeignKey(Article)
likes = models.IntegerField(default = 0)
def __str__(self):
return self.Likes
现在我呈现出来的网页,但我想显示有多少喜欢每一篇文章。我怎样才能加入这两种模式。更改对象。全部方法也从Like模型中获取Like
你可以使用FOO\u set,docs about this here,基本上你这样做是为了得到所有的喜欢:
您可以使用count()来获取数字
首先,您可能希望将article\u id重命名为article,因为当您使用该属性时,实际上您将获得article,而不仅仅是id
在这种情况下,你似乎有一个多对一之间的关系喜欢和文章。这意味着您需要将likes称为“like\u set”。因此,如果您碰巧将对象存储在article中,则可以使用
article.like_set.all()
获得所有like,使用article.like_set.count()
获得count。你知道吗引用:https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_one/
如果您有兴趣提前获取此信息,可以使用prefetch\u related保存其他数据库调用:
https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related
它会像这样:
articles = Article.objects.all().prefetch_related('like_set')
相关问题 更多 >
编程相关推荐