您有几个选择如何解决这个问题。我将专注于捅代码的问题,因为我已经用django内部的东西去了一段时间。
我在下面的链接中包含了相关代码。请注意,我删除了不相关的部分。另请注意,您将要编辑的部分是您的案例需要重构。
请遵循以下算法,直到您满意为止。
- 重构
if
声明取决于(一个或多个)单独函数的字段。
- 添加检查代码,直到找出哪些字段对应于一般关系。
- 添加提取代码,直到遵循泛型关系。
测试。
def handle_models(self, models, **options):
# SNIP handle options
all = objects
if propagate:
collected = set([(x.__class__, x.pk) for x in all])
while objects:
related = []
for x in objects:
if DEBUG:
print "Adding %s[%s]" % (model_name(x), x.pk)
# follow forward relation fields
for f in x.__class__._meta.fields + x.__class__._meta.many_to_many:
# YOU CASE HERE
if isinstance(f, ForeignKey):
new = getattr(x, f.name) # instantiate object
if new and not (new.__class__, new.pk) in collected:
collected.add((new.__class__, new.pk))
related.append(new)
if isinstance(f, ManyToManyField):
for new in getattr(x, f.name).all():
if new and not (new.__class__, new.pk) in collected:
collected.add((new.__class__, new.pk))
related.append(new)
# SNIP
objects = related
all.extend(objects)
# SNIP serialization
请编辑问题,包括相关的源。我不打算通过点击访问其他网站来查看你在说什么,对于有同样问题的人来说,以这种方式发现这个问题更加困难。 – 2011-05-22 08:23:13
你应该添加一些关于你的问题的细节,你到底有什么问题? – 2011-07-08 19:18:06