暴露“虚拟"饼视图中的字段? [英] Exposing "virtual" field in a tastypie view?

查看:35
本文介绍了暴露“虚拟"饼视图中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个视图,使用asteapie公开某些相同类型的对象,但是要使用以下 two 三点曲折:

I want to create a view using tastypie to expose certain objects of the same type, but with the following two three twists:

  1. 我需要使用三个单独的查询来获取对象;
  2. 我需要添加一个基础模型中不存在的字段,该字段的值取决于它来自哪个查询;和
  3. 数据将按用户显示(因此,我需要挂接到获取请求的方法之一).

我不清楚如何融入好吃的生命周期来完成此任务.推荐的添加虚拟"字段的方法是在脱水方法中,该方法仅知道其正在操作的束.

I'm not clear on how to hook into the tastypie lifecycle to accomplish this. The recommended way for adding a "virtual" field is in the dehydrate method, which only knows about the bundle it's operating on.

更糟糕的是,没有正式的方式来加入查询集.

Even worse, there's no official way to join querysets.

如果我可以让好吃的人接受除查询集以外的东西,我的问题就会消失.在那种情况下,我可以将其对象的子类列表传递给它,并添加其他字段.

My problem would go away if I could get tastypie to accept something other than a queryset. In that case I could pass it a list of subclasses of my object, with the additional field added.

我愿意接受任何其他明智的解决方案.

I'm open to any other sensible solution.

添加了扭曲3-每个用户的数据.

Added twist 3 - per-user data.

推荐答案

好的,所以这是我的解决方案.代码在下面.

OK, so this is my solution. Code is below.

注意事项:

  1. 这项工作基本上都是在 obj_get_list 中完成的.那是我运行查询并可以访问请求的地方.
  2. 我可以从 obj_get_list 返回列表.
  3. 我可能必须重写与其他操作相对应的所有其他 obj _ * 方法(例如 obj_get obj_create 等)如果我希望它们可用.
  4. 因为我在 Meta 中没有 queryset ,所以我需要提供一个 object_class 来告诉好吃的人自省提供哪些字段.
  5. 要公开我的虚拟"属性(在 obj_get_list 中创建),我需要为其添加字段声明.
  6. 我已注释掉过滤器和授权限制,因为我现在不需要它们.如果需要,我需要自己实施.
  1. The work is basically all done in obj_get_list. That's where I run my queries, having access to the request.
  2. I can return a list from obj_get_list.
  3. I would probably have to override all of the other obj_* methods corresponding to the other operations (like obj_get, obj_create, etc) if I wanted them to be available.
  4. Because I don't have a queryset in Meta, I need to provide an object_class to tell tastypie's introspection what fields to offer.
  5. To expose my "virtual" attribute (which I create in obj_get_list), I need to add a field declaration for it.
  6. I've commented out the filters and authorisation limits because I don't need them right now. I'd need to implement them myself if I needed them.

代码:

from tastypie.resources import ModelResource
from tastypie import fields
from models import *
import logging

logger = logging.getLogger(__name__)


class CompanyResource(ModelResource):
    role = fields.CharField(attribute='role')


    class Meta:
        allowed_methods = ['get']
        resource_name = 'companies'
        object_class = CompanyUK
        # should probably have some sort of authentication here quite soon


    #filters does nothing. If it matters, hook them up
    def obj_get_list(self, request=None, **kwargs):
#         filters = {}

#         if hasattr(request, 'GET'):
#             # Grab a mutable copy.
#             filters = request.GET.copy()

#         # Update with the provided kwargs.
#         filters.update(kwargs)
#         applicable_filters = self.build_filters(filters=filters)

        try:
            #base_object_list = self.get_object_list(request).filter(**applicable_filters)
            def add_role(role):
                def add_role_company(link):
                    company = link.company
                    company.role = role
                    return company
                return add_role_company

            director_of = map(add_role('director'), DirectorsIndividual.objects.filter(individual__user=request.user))
            member_of   = map(add_role('member'),   MembersIndividual.objects.filter(individual__user=request.user))
            manager_of  = map(add_role('manager'),  CompanyManager.objects.filter(user=request.user))

            base_object_list = director_of + member_of + manager_of
            return base_object_list #self.apply_authorization_limits(request, base_object_list)
        except ValueError, e:
            raise BadRequest("Invalid resource lookup data provided (mismatched type).")

这篇关于暴露“虚拟"饼视图中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆