Py学习  »  Django

[精华] 求一条查询数据库的语句

sincerefly • 10 年前 • 8106 次点击  

定义回复模型是这样的

class Reply(models.Model):
    content = models.TextField()
    author = models.ForeignKey(User)
    topic = models.ForeignKey(Topic)
    has_parent = models.BooleanField(default=False)
    parent = models.ForeignKey('self',null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    thanks = models.ManyToManyField(User,related_name='+')

每个reply就是一个topic的回复。每获得一个赞同那么thinks就多一个人

我如何能通过指定用户然后过滤出所有他的回复,然后获得他获得赞同的总数

尝试了半天也没成功。求帮忙呀


Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/677
 
8106 次点击  
文章 [ 8 ]  |  最新文章 10 年前
sincerefly
Reply   •   1 楼
sincerefly    10 年前

@Django中国社区 嗯,等以后再慢慢想别的办法吧,先这样凑合用。

Py站长
Reply   •   2 楼
Py站长    10 年前

@sincerefly 如果列表人太多,你这样速度有点差哦。不过流量可以先这样:)

sincerefly
Reply   •   3 楼
sincerefly    10 年前

@Django中国社区 感谢你的回复,昨晚无意间想到个思路,早上起来弄了一会搞定了。

就是在models中的UserProfile定义一个方法。

class UserProfile(models.Model):
user = models.OneToOneField(User)

def get_user_thanks(self):
    thanks_count = 0
    for reply in Reply.objects.filter(author=self.user):
        thanks_count += reply.thanks.count()
    return thanks_count

这样在模板中可以通过{{ item.author.userprofile.get_user_thanks }}获取。item是Reply的实例。

Py站长
Reply   •   4 楼
Py站长    10 年前

@sincerefly 可以这么做的。

你找不到方法是因为,你需要计算好多人的数据,这样就是N*M个循环,速度 非常差。

两种做法,一种就是数据冗余,就像你说的,这种就是更新数据时多一步操作,但是读取时非常 方便。另一种可以用nosql进行记录。

你可以使用第一种。

sincerefly
Reply   •   5 楼
sincerefly    10 年前

@Django中国社区 有点问题想请教,也和这个帖子的内容有关,我就在这里继续问了。

是这样的。如果进入用户的个人界面,那么上面这种方法是可以使用的。但是首页如果显示多个人及获赞数。则在view和视图中我都想不到处理方法,。

所以我想是不是应该在models中user多加个like来保存总共的赞数。

像这种情况。这个like应该怎么定义呢。而且它的值要怎么获取并保存起来呢。

sincerefly
Reply   •   6 楼
sincerefly    10 年前
thanks_count = 0
for reply in Reply.objects.filter(author=user_profile.user):
    thanks_count += reply.thanks.count()

解决了。

sincerefly
Reply   •   7 楼
sincerefly    10 年前

@mihello Thx~

mihello
Reply   •   8 楼
mihello    10 年前

参考: http://djangobook.py3k.cn/2.0/chapter10/