gpt4 book ai didi

django - 在 Tastypie 中序列化 django-mptt 树

转载 作者:行者123 更新时间:2023-12-04 23:24:26 25 4
gpt4 key购买 nike

我如何序列化 django-mptt树木在Tastypie ?

我想用django-mpttcache_tree_children() .我尝试在不同的 Tastypie Hook 中应用,但它会引发错误。

最佳答案

没有 cache_tree_children您可以通过简单地连接 ToManyField 来序列化您的 child 的方法。与 full=True指着 children属性(property):

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()

实现 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

这种方法的主要优点之一是您不必再关心细节/ ListView 约束/差异。您甚至可以进一步参数化资源的这一方面,直到获得某种符合您需求的默认行为。基于字段,即。我认为这很酷。

关于django - 在 Tastypie 中序列化 django-mptt 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com