QuerySet对象没有属性序列化

时间:2019-01-23 10:18:56

标签: django-rest-framework

  

views.py

import json
from django.shortcuts import get_object_or_404
from django.core.serializers import serialize
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.views.generic import View
from RestAPI.mixin import JsonResponseMixIn
from .models import Update   

class SerializedListView(View):
    def get(self , request , *args , **kwargs):
        qs = Update.objects.all()
        qs = qs.serialize() #error in this line
        return HttpResponse(qs , content_type="application/json")

serialize方法与get()方法可以正常工作,但是在all()方法中抛出错误

异常值:
'QuerySet'对象没有属性'serialize'

  

models.py

import json
from django.core.serializers import serialize
from django.db import models
from django.conf import settings

# Create your models here.



class UpdateQuerySet(models.QuerySet):
    def serialize(self):
        list_values = list(self.values("uesr","content","image"))
        return json.dumps(list_values)

class UpdateManager(models.Manager):
    def get_queryset(self):
        return UpdateQuerySet(self.model, using=self._db)

2 个答案:

答案 0 :(得分:0)

我认为最好定义一个serializer并获取如下数据:

class UpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Update
        fields = ("user", "content", "schedule", "image")

,并在view中更改为:

class SerializedListView(View):
    def get(self , request , *args , **kwargs):
        qs = Update.objects.all()
        serializer = UpdateSerializer(qs, many=True)
        return HttpResponse(serializer.data , content_type="application/json")

答案 1 :(得分:0)

class Update(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    content = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to=upload_update_image, blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    objects = UpdateManager()

    def __str__(self):
        return self.content or ""

在模型中必须具有对象= UpdateManager()才能起作用。