Django Fixtures如何处理ManyToManyFields?

时间:2011-10-05 00:15:31

标签: django many-to-many models fixtures

我正在尝试将来自clinicaltrials.gov的大约30k xml文件加载到mySQL数据库中,我处理多个位置,关键字等的方式是使用ManyToManyFields的单独模型。

我想到的最好的方法是使用夹具读取数据。所以我的问题是,如何处理数据是指向另一个模型的指针的字段?

遗憾的是,我对ManyToMany / ForeignKeys的工作原理不太了解,能够回答......

感谢您的帮助,示例代码如下: _ _代表ManyToMany字段

{
    "pk": trial_id,
    "model": trials.trial,
    "fields": {
            "trial_id": trial_id,
            "brief_title": brief_title,
            "official_title": official_title,
            "brief_summary": brief_summary,
            "detailed_Description": detailed_description,
            "overall_status": overall_status,
            "phase": phase,
            "enrollment": enrollment,
            "study_type": study_type,
            "condition": _______________,
            "elligibility": elligibility,
            "Criteria": ______________,
            "overall_contact": _______________,
            "location": ___________,
            "lastchanged_date": lastchanged_date,
            "firstreceived_date": firstreceived_date,
            "keyword": __________,
            "condition_mesh": condition_mesh,
    }

}

1 个答案:

答案 0 :(得分:19)

外键很简单,你要链接的对象的pk,manytomanyfield使用pk的列表。所以

[
    {
        "pk":1,
        "model":farm.fruit,
        "fields":{
            "name" : "Apple",
            "color" : "Green",
        }
    },
    {
        "pk":2,
        "model":farm.fruit,
        "fields":{
            "name" : "Orange",
            "color" : "Orange",
        }
    },
    {
         "pk":3,
         "model":person.farmer,
         "fields":{
             "name":"Bill",
             "favorite":1,
             "likes":[1,2],
         }
    }
]

您可能需要编写转换脚本才能完成此操作。固定装置可能非常脆弱;在花费大量时间转换30k记录之前,很难让这个实验用一个子集进行实验(只是发现它们可能无法导入)