不确定区别是什么,但我有两段代码,我认为应该表现相同。
这有效:
channels = RpChannels.objects.using('prod').all().filter(userid=id).order_by('-when')
for channel in channels:
date = channel.t.replace(",","-") if channel.t else "Default"
name = Playlists.objects.using('prod').get(id=channel.p).description if channel.p else "Default"
genres = ', '.join(StTag.objects.values_list('tag', flat = True).filter(id__in=channel.g.split(',')).order_by('tag')) if channel.g else "Default"
when = channel.when if channel.when else "N/A"
setattr(channel, 'channel', name)
setattr(channel, 'genres', genres)
setattr(channel, 'date', date)
setattr(channel, 'when', when)
setattr(channel, 'valence', channel.v if channel.v else "Default")
setattr(channel, 'arousal', channel.a if channel.a else "Default")
context = {'st_user': user,
'devices': devices,
'feedback': feedback,
'stations': stations,
'channels': channels}
return render(request, 'user.html', context)
这不是:
tracks = Songplays.objects.using('prod').all().filter(user=id, when__gt=start, when__lt=end).order_by('-when')
for item in tracks:
track = Track.objects.get(id=item.trackid)
artist = Artist.objects.get(id=track.artist_id).name
title = TrackTitle.objects.get(id=track.id).title
setattr(item, 'duration', str(datetime.timedelta(seconds=track.duration)) if track.duration else "N/A")
setattr(item, 'title', title)
setattr(item, 'artist', artist)
data = serializers.serialize('json', tracks)
return HttpResponse(data, mimetype="application/json")
我的意思是不起作用,例如在第一个中没有setattr值存在,但它们被添加到每个单独的通道,我可以在我的模板中访问它们。但是,在第二段代码持续时间存在,以便修改后的值在我的JSON中输出,但其他2个属性,标题和艺术家,在原始查询集中不存在,但与通道不同,它们不会被添加。我可以和它呈现的方式有什么关系吗?如果是这样,为什么?
答案 0 :(得分:2)
由于序列化程序仅使用模型字段,因此我决定返回一个ValuesQuerySet而不是QuerySet,因为前者返回一个dict。我通过获取values()而不是all()来完成此操作。感谢@PeterDeGlopper指出我正确的方向!
# this
tracks = Songplays.objects.using('prod').values().filter(user=id, when__gt=start, when__lt=end).order_by('-when')
#instead of this
tracks = Songplays.objects.using('prod').all().filter(user=id, when__gt=start, when__lt=end).order_by('-when')
一旦我有了dict,我就可以像这样转换为JSON。
import json
data = json.dumps(list(tracks))