我正在尝试为django-test-utils makefixture命令添加泛型关系和一对一关系支持,这里是源http://github.com/ericholscher/django-test-utils/blob/master/test_utils/management/commands/makefixture.py
有人有想法如何做到这一点?或者可能还有另一种工具:
./manage.py dumpcmd User[:10] > fixtures.json
答案 0 :(得分:1)
您可以通过多种方式解决问题。我将专注于 poke-the-code aproach,因为我已经用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