一、
往queryset里每一个对象添加新属性
如下两个model
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="评论者id")
article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="文章id")
parent_comment = models.ForeignKey("self", on_delete=models.CASCADE, null=True, verbose_name="父评论")
content = models.TextField(verbose_name="评论内容")
comment_time = models.DateTimeField(auto_now_add=True, verbose_name="评论时间")
is_deleted = models.SmallIntegerField(default=0, verbose_name="是否已删除")
class Meta:
ordering = ["-comment_time"]
class CommentFeedBack(models.Model):
comment = models.ForeignKey(Comment, verbose_name="评论id", on_delete=models.CASCADE)
user = models.ForeignKey(User, verbose_name="用户id", on_delete=models.CASCADE)
feed_back = models.SmallIntegerField(verbose_name="反馈", help_text="0-未评 1-好评 2-差评")
获取每个评论及其好评与差评数
comments = Comment.objects.filter(article_id=id)
for comment in comments:
comment.good_view = CommentFeedBack.objects.filter(comment_id=comment.id, feed_back=1).count()
comment.bad_view = CommentFeedBack.objects.filter(comment_id=comment.id, feed_back=2).count()
二、字段改名
from django.db.models import F
query_set.values(new_name=F(old_name))
例如:
有如下model
class Category(models.Model):
name = models.CharField(max_length=20, verbose_name='类名')
is_deleted = models.SmallIntegerField(default=0, verbose_name='是否已删除')
class Article(models.Model):
title = models.CharField(max_length=120, verbose_name='标题')
category = models.ForeignKey(Category, verbose_name='分类', on_delete=models.CASCADE)
add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
is_deleted = models.SmallIntegerField(default=0, verbose_name='是否已删除',
help_text='0-未删除 1-已删除')
Article.objects.filter(is_deleted=0).values(category_name=F("category__name"))
即可将category__name这个不好看的名字改为category_name
但是有个问题是如果只是获取一条数据,使用model.objects.get()操作是不能使用values操作的,此时可以像如下进行获取:
Article.objects.filter(id=164).values(category_name=F("category__name"))[0]
或者
Article.objects.filter(id=164).values(category_name=F("category__name")).first()
三、将查询的数据按其中某一个字段分组
如下model
class ActionGroup(models.Model):
group = models.CharField(max_length=32, verbose_name='动作组名')
class Meta:
verbose_name = "动作组表"
verbose_name_plural = verbose_name
class Right(models.Model):
url = models.CharField(max_length=32, verbose_name='路由')
action = models.CharField(max_length=32, verbose_name='名称')
type = models.CharField(max_length=8, verbose_name='请求方式')
action_group = models.ForeignKey(ActionGroup, verbose_name='动作组', on_delete=models.CASCADE)
按动作组即action_group对权限进行分组,此时要用到defaultdict
from collections import defaultdict
rights = Right.objects.all().values("id", "action_group_id", "action_group__group", "action")
res = defaultdict(list)
for right in rights:
res[right['action_group_id']].append((right['id'], right['action_group__group'], right['action']))
defaultdict是当没有这个key是自动添加,list说明它的key是一个list.
将res返回给前端时记得dict(res)一下。