2010-09-25 128 views
7

我想补充的通用关系和Django的测试-utils的makefixture命令一到一个关系的支持,这是源http://github.com/ericholscher/django-test-utils/blob/master/test_utils/management/commands/makefixture.pyDjango的,通用的关系,使灯具

是否有人有想法如何做这个?或者可能有另一种工具,如:

./manage.py dumpcmd User[:10] > fixtures.json 
+1

请编辑问题,包括相关的源。我不打算通过点击访问其他网站来查看你在说什么,对于有同样问题的人来说,以这种方式发现这个问题更加困难。 – 2011-05-22 08:23:13

+0

你应该添加一些关于你的问题的细节,你到底有什么问题? – 2011-07-08 19:18:06

回答

1

您有几个选择如何解决这个问题。我将专注于捅代码的问题,因为我已经用django内部的东西去了一段时间。

我在下面的链接中包含了相关代码。请注意,我删除了不相关的部分。另请注意,您将要编辑的部分是您的案例需要重构。

请遵循以下算法,直到您满意为止。

  1. 重构if声明取决于(一个或多个)单独函数的字段。
  2. 添加检查代码,直到找出哪些字段对应于一般关系。
  3. 添加提取代码,直到遵循泛型关系。
  4. 测试。

    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