Django:使用一些自定义列序列化queryset并格式化一些字段 [英] Django: serialize queryset with some custom columns and format some fields

查看:51
本文介绍了Django:使用一些自定义列序列化queryset并格式化一些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django> 2项目中具有以下模型:

I have the following models in my Django > 2 Project:

class Post(models.Model):
  text = models.TextField()
  date = models.DatetimeField(default=datetime.now, blank=True)

class Like(models.Model):
  post = models.ForeignKey(Post)
  user = models.ForeignKey(User, related_name="current_user_likes")

我想发送帖子列表的JSON响应.并且还为登录的用户显示每个帖子(无论是否喜欢).

I want to send a JSON response of list of Posts. And also show for each post, whether if already liked or not, by the user who logged in.

我希望帖子列表包含请求的布尔值字段"current_user_like".用户.

I want the list of Posts to contain a boolean field "current_user_like" for the request.user, .

我正在使用以下方式来创建帖子的查询集,无论特定用户是否喜欢.与 https://stackoverflow.com/a/33944811/2897115

I am using the following way to create the queryset of Posts with, whether liked or not by a particular user. Same way as https://stackoverflow.com/a/33944811/2897115

posts = Post.objects.all().prefetch_related(
    Prefetch('current_user_likes', queryset=Like.objects.filter(user=request.user))
)

我期望的是JSON,如下所示:

i am expecting a JSON as below:

[ {"id":1, "text":"sample", "date":"whateverformat i want i.e YY-MM-DD","current_user_likes":"true/false"} ........]

因此,希望Json具有格式化的日期,并且还添加了"current_user_likes"字段.

So want the Json with formated date and also added field of "current_user_likes".

操作方法

推荐答案

对于日期格式,您可以直接使用 .annotate()并使用一些DB函数来转换格式.

For date formatting you can directly use .annotate() and use some DB function to convert in your format.

对于这样的建议,我建议使用 Exists 并放入 annotate()

For the like I'd suggest to use Exists and put in annotate()

抱歉,我无法检查语法,但这应该可以正常工作

Sorry I cannot check the syntax but this should almost work

qs = Post.objects.all()
sub = Like.objects.filter(post__id=OuterRef('pk'), user=request.user)

values = qs.annotate(
    date=Func(F('date'), function='db_specific_date_formatting_func'),
    current_user_like=Exists(sub)
).values('text, 'date', 'current_user_like')

这篇关于Django:使用一些自定义列序列化queryset并格式化一些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆