【问题标题】:Django, generic relations, make fixturesDjango,泛型关系,制作夹具
【发布时间】:2011-04-17 04:48:51
【问题描述】:

我正在尝试为 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

【问题讨论】:

  • 请编辑问题以包含相关来源。我不会为了看看你在说什么而努力点击其他网站,而且对于和你有同样问题的人来说,通过这种方式发现这个问题会更加困难。
  • 你应该添加一些关于你的问题的细节,你到底有什么问题?

标签: django fixtures django-testing django-fixtures


【解决方案1】:

您有多种解决问题的方法。我将专注于 poke-the-code 方法,因为我已经有一段时间没有研究 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
    

【讨论】:

    猜你喜欢
    • 2011-09-29
    • 2012-03-20
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多