返回JsonResponse时,如何使查询集在django中也包含PK

时间:2018-01-12 10:29:34

标签: django django-models django-queryset

我有这个型号:

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username')
    video = models.ForeignKey(Video, on_delete=models.CASCADE)
    description = models.TextField(default="none")
    replyto = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE)
    uploaded = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True) # maybe add ability to update comments...
    indent = models.IntegerField(default=0)

我必须返回一个这样的查询集来创建一个JsonResponse:

Comment.objects.filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end]

我将此作为响应(在将其序列化为json并将其作为响应发送给Ajax请求之后)。

Object { user: "TestUser", video: 7, description: "test new video comment lol", replyto: 5, uploaded: "2018-01-12T09:14:24.281Z", updated: "2018-01-12T09:14:24.281Z", indent: 0 }
Object { user: "admin", video: 7, description: "testing the new comment system per …", replyto: null, uploaded: "2018-01-12T09:14:05.740Z", updated: "2018-01-12T09:14:05.740Z", indent: 0 }

但是我想在值列表中包含每个对象的PK。所以我试过了:

Comment.objects.value_list('pk','user','video','description','replyto','uploaded','updated','indent').filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end]

导致错误:

AttributeError: 'Manager' object has no attribute 'value_list'
这是为什么?如何获得一个还包含PK的查询集?

修改

按要求:这是序列化对象的代码:

def obtain_comments(request, *args, **kwargs):
    begin = int(request.GET['begin'])
    end = int(request.GET['end'])
    # check if end is less than number of comments and begin is more or equal than 0
    n_comments = end - begin
    all_split = Comment.objects.filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end]
    data = {
        'comments': serializers.serialize('json',all_split),
    }
    return JsonResponse(data)

1 个答案:

答案 0 :(得分:0)

您可以将字段列表发送到serializers.serialize。然后你的代码将是:

def obtain_comments(request, *args, **kwargs):
    begin = int(request.GET['begin'])
    end = int(request.GET['end'])
    # check if end is less than number of comments and begin is more or equal than 0
    n_comments = end - begin
    all_split = Comment.objects.filter(video__identifier=request.GET['identifier']).order_by('-uploaded')[:end]
    data = {
        'comments': serializers.serialize('json', all_split, fields=(
            'pk', 'user', 'video', 'description', 'replyto', 'uploaded', 'updated', 'indent'))
    }
    return JsonResponse(data)