【问题标题】:Django: 'QuerySet' object has no attribute 'serialize'Django:“QuerySet”对象没有“序列化”属性
【发布时间】:2020-06-20 23:51:53
【问题描述】:

models.py

class UpdateQuerySet(models.QuerySet):
    def serialize(self):
        qs = self
        return serialize('json', qs, fields=('user', 'content', 'image'))

class UpdateManager(models.Manager):
    def get_queryset(self):
        return UpdateQuerySet(self.model, using=self._db)
class Tools_booked(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    user=models.ForeignKey(Profile, on_delete=models.CASCADE)
    component = models.CharField(max_length=30, blank=True)
    booked = models.DateTimeField(auto_now_add=True,blank=True)

    objects = UpdateManager()

    def __str__(self):
        return self.component

    def serialize(self):
        return serialize("json", [self], fields=['auto_increment_id','user','component','booked'])

views.py

from django.core.serializers import serialize
class SerializedDetialView(View):
     def get(self, request, *args, **kwargs):
        obj = Tools_booked.objects.get(auto_increment_id=1)
        json_data = obj.serialize()
        return HttpResponse(json_data, content_type='application/json')


class SerializedListView(View):
     def get(self, request, *args, **kwargs):
        qs = Tools_booked.objects.all()
        json_data = qs.serialize()
        return HttpResponse(json_data, content_type='application/json')

我已经看到了类似的问题,它是用新的类视图解决的。但是为什么这段代码不起作用。它为 SerializedListView 和 SerializedDetialView url 显示的错误是

'QuerySet' object has no attribute 'serialize'

'Tools_booked' object has no attribute 'serialize'

为什么会出现这个错误,我们如何在不创建新类的情况下解决这个错误。

编辑

in views.py, line 84, in get
    json_data = qs.serialize()
    AttributeError: 'QuerySet' object has no attribute 'serialize'

【问题讨论】:

  • 请编辑问题并完整追溯您的错误。
  • @ans2human 添加了回溯

标签: django django-models django-views django-serializer


【解决方案1】:

https://docs.djangoproject.com/en/3.0/topics/serialization/#serializing-data

from django.core import serializers

obj_list= Tools_booked.objects.filter(auto_increment_id=1)
json_data = serializers.serialize("json", obj_list )
return HttpResponse(json_data, content_type='application/json')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2021-08-05
    • 2017-06-22
    • 2013-05-10
    • 1970-01-01
    • 2021-07-09
    • 2011-12-14
    相关资源
    最近更新 更多