使用嵌套类将模型序列化为 json 不会公开嵌套类

发布于 2024-11-01 05:05:45 字数 3580 浏览 0 评论 0原文

摘要: 问题是我无法从序列化模型中的嵌套类访问缩略图,并且我不知道如何在 JSON 响应中公开它。

<描述:我正在尝试将我的 Thing 模型序列化为 JSON,并且它以某种方式工作。我在 JSON 响应中得到以下内容:

// JSON response
[
    {
        pk: 1
        model: "base.thing"
        fields: {
            active: true
            created_at: "2011-04-13 07:18:05"
            num_views: 1
            file: "things/5216868239_b53b8d5e80_b.jpg"
            title: "ding ding ding"
        }
    }
]

我刚刚开始使用 django-imagekit 将 Thing 图像操作为缩略图大小,并且它可以正常使用,即在模板中运行“thing.thumbnail_image.url”会返回缩略图的正确 url图像。

我正在使用的沙箱代码:

# base/models.py
from django.db import models
from imagekit.models import ImageModel

class Thing(ImageModel):
    title = models.CharField(max_length=30)
    file = models.ImageField(upload_to='things')
    created_at = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField()
    num_views = models.PositiveIntegerField(editable=False, default=0)

    def __unicode__(self):
        return self.title

    class IKOptions:
        spec_module = 'base.specs'
        image_field = 'file'
        save_count_as = 'num_views'

# base/views.py
from django.views.generic.base import View
from django.views.generic.list import MultipleObjectTemplateResponseMixin, ListView

from base.models import Thing    
from django import http
from django.utils import simplejson as json

from utils import JsonResponse

class JSONResponseMixin(object):
    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(context)

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return JsonResponse(content['thing_list']) # I can't serialize the content object by itself

class ThingsView(JSONResponseMixin, ListView):
    model = Thing
    context_object_name = "thing_list"
    template_name = "base/thing_list.html"

    def render_to_response(self, context):
        if self.request.GET.get('format', 'html') == 'json':
            return JSONResponseMixin.render_to_response(self, context)
        else:
            return ListView.render_to_response(self, context)

# base/specs.py
from imagekit.specs import ImageSpec
from imagekit import processors

class ResizeThumb(processors.Resize):
    width = 100
    height = 75
    crop = True

class ResizeDisplay(processors.Resize):
    width = 600

class EnchanceThumb(processors.Adjustment):
    contrast = 1.2
    sharpness = 1.1

class Thumbnail(ImageSpec):
    access_as = 'thumbnail_image'
    pre_cache = True
    processors = [ResizeThumb, EnchanceThumb]

class Display(ImageSpec):
    increment_count = True
    processors = [ResizeDisplay]

# utils.py
from django.core.serializers import json, serialize
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.utils import simplejson

class JsonResponse(HttpResponse):
    def __init__(self, object):
        if isinstance(object, QuerySet):
            content = serialize('json', object)
        else:
            content = simplejson.dumps(
                object, indent=2, cls=json.DjangoJSONEncoder,
                ensure_ascii=False)
        super(JsonResponse, self).__init__(
            content, content_type='application/json')

我感谢任何有关此问题的帮助,它已经阻止了我一天。

此致-

使用版本:
Django 1.3
PIL 1.1.7
django-imagekit 0.3.6
simplejson 2.1.3

Summary: The problem is that I cannot access the thumbnail image from a nested class in the serialized model and I don't know how to expose it in the JSON response.

Description: I am trying to serialize my Thing model to JSON and it works, in a fashion. I get the following in my JSON response:

// JSON response
[
    {
        pk: 1
        model: "base.thing"
        fields: {
            active: true
            created_at: "2011-04-13 07:18:05"
            num_views: 1
            file: "things/5216868239_b53b8d5e80_b.jpg"
            title: "ding ding ding"
        }
    }
]

I just started using django-imagekit to manipulate the Thing images to thumbnail sizes and it works in normal usage, i.e. running 'thing.thumbnail_image.url' in a template returns the correct url to the thumbnail image.

The sandbox code I'm playing around with:

# base/models.py
from django.db import models
from imagekit.models import ImageModel

class Thing(ImageModel):
    title = models.CharField(max_length=30)
    file = models.ImageField(upload_to='things')
    created_at = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField()
    num_views = models.PositiveIntegerField(editable=False, default=0)

    def __unicode__(self):
        return self.title

    class IKOptions:
        spec_module = 'base.specs'
        image_field = 'file'
        save_count_as = 'num_views'

# base/views.py
from django.views.generic.base import View
from django.views.generic.list import MultipleObjectTemplateResponseMixin, ListView

from base.models import Thing    
from django import http
from django.utils import simplejson as json

from utils import JsonResponse

class JSONResponseMixin(object):
    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(context)

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return JsonResponse(content['thing_list']) # I can't serialize the content object by itself

class ThingsView(JSONResponseMixin, ListView):
    model = Thing
    context_object_name = "thing_list"
    template_name = "base/thing_list.html"

    def render_to_response(self, context):
        if self.request.GET.get('format', 'html') == 'json':
            return JSONResponseMixin.render_to_response(self, context)
        else:
            return ListView.render_to_response(self, context)

# base/specs.py
from imagekit.specs import ImageSpec
from imagekit import processors

class ResizeThumb(processors.Resize):
    width = 100
    height = 75
    crop = True

class ResizeDisplay(processors.Resize):
    width = 600

class EnchanceThumb(processors.Adjustment):
    contrast = 1.2
    sharpness = 1.1

class Thumbnail(ImageSpec):
    access_as = 'thumbnail_image'
    pre_cache = True
    processors = [ResizeThumb, EnchanceThumb]

class Display(ImageSpec):
    increment_count = True
    processors = [ResizeDisplay]

# utils.py
from django.core.serializers import json, serialize
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.utils import simplejson

class JsonResponse(HttpResponse):
    def __init__(self, object):
        if isinstance(object, QuerySet):
            content = serialize('json', object)
        else:
            content = simplejson.dumps(
                object, indent=2, cls=json.DjangoJSONEncoder,
                ensure_ascii=False)
        super(JsonResponse, self).__init__(
            content, content_type='application/json')

I appreciate any help with this, it's been blocking me for a day.

Best regards-

Using versions:
Django 1.3
PIL 1.1.7
django-imagekit 0.3.6
simplejson 2.1.3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小ぇ时光︴ 2024-11-08 05:05:45

我不知道如何通过 JSON 公开内部类,因此我选择了另一种方法,即删除 django-imagekit 并手动将图像大小调整为缩略图并将其保存在模型的 save() 函数中。

im = ImageOps.fit(im, (sizes['thumbnail']['width'], sizes['thumbnail']['height'],), method=Image.ANTIALIAS)
thumbname = filename + "_" + str(sizes['thumbnail']['width']) + "x" + str(sizes['thumbnail']['height']) + ".jpg"
im.save(fullpath + '/' + thumbname)

这是一种不太干净的方法,但目前有效。

I couldn't figure out how to expose the inner class over JSON so I chose an alternative way of doing it and dropping django-imagekit and manually resizing the image to a thumbnail and saving it in the model's save() function.

im = ImageOps.fit(im, (sizes['thumbnail']['width'], sizes['thumbnail']['height'],), method=Image.ANTIALIAS)
thumbname = filename + "_" + str(sizes['thumbnail']['width']) + "x" + str(sizes['thumbnail']['height']) + ".jpg"
im.save(fullpath + '/' + thumbname)

It's a less than clean approach but it works for now.

你与清晨阳光 2024-11-08 05:05:45

我认为您正在寻找类似 的结果,它正在加载图像的完整路径,如 " /media/images/2013/photo_01.jpg“。使用 JSON,您只有存储在数据库模型中的路径。

您可以做的是在模板中添加一些前缀,例如

I think that you are looking for a result like <img src="{{ product.photo.url }}"/> which is loading the full path to your images like "/media/images/2013/photo_01.jpg". With JSON you have only the path which is stored in you database model.

What you can do is add some prefix in the template like <img src="media/{{ product.photo.url }}"/>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文