dan*_*son 4 django django-mptt tastypie
如何序列化django-mptt树Tastypie?
我想用django-mptt的cache_tree_children().我尝试过应用不同的Tastypie钩子,但它会抛出一个错误.
没有cache_tree_children方法,你很可能有你的孩子连载通过简单地钩住了ToManyField与full=True在指向children特性:
class MenuResource(ModelResource):
children = fields.ToManyField('self', 'children', null=True, full=True)
parent = fields.ToOneField('self', 'parent', null=True)
class Meta:
queryset = Menu.objects.all()
Run Code Online (Sandbox Code Playgroud)
要实现该cache_tree_children函数,您可以编写自己的ToManyField子类来覆盖标准dehydrate函数.请注意,我只是非常表面地测试了这个解决方案:
def dehydrate(self, bundle):
if not bundle.obj or not bundle.obj.pk:
if not self.null:
raise ApiFieldError("The model '%r' does not have a primary key and can not be used in a ToMany context." % bundle.obj)
return []
the_m2ms = None
previous_obj = bundle.obj
attr = self.attribute
if isinstance(self.attribute, basestring):
attrs = self.attribute.split('__')
the_m2ms = bundle.obj
for attr in attrs:
previous_obj = the_m2ms
try:
the_m2ms = getattr(the_m2ms, attr, None)
except ObjectDoesNotExist:
the_m2ms = None
if not the_m2ms:
break
elif callable(self.attribute):
the_m2ms = self.attribute(bundle)
if not the_m2ms:
if not self.null:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (previous_obj, attr))
return []
self.m2m_resources = []
m2m_dehydrated = []
# There goes your ``cache_tree_children``
for m2m in cache_tree_children(the_m2ms.all()):
m2m_resource = self.get_related_resource(m2m)
m2m_bundle = Bundle(obj=m2m, request=bundle.request)
self.m2m_resources.append(m2m_resource)
m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource))
return m2m_dehydrated
Run Code Online (Sandbox Code Playgroud)
这种方法的一个主要优点是您不必再关心细节/列表视图约束/差异.您甚至可以进一步参数化资源的这一方面,直到您获得某种符合您需求的默认行为.基于现场,即.我认为这很酷.
| 归档时间: |
|
| 查看次数: |
980 次 |
| 最近记录: |