如何在现有的django模型中添加ManyToManyField?

时间:2012-03-25 16:14:03

标签: django django-models

我有两张桌子:

class Visit(models.Models):

    date_created            = models.DateTimeField(auto_now_add=True)
    date_modified           = models.DateTimeField(auto_now=True)
    date_started            = models.DateTimeField(null=True, blank=True)
    date_completed          = models.DateTimeField(null=True, blank=True)
    # Here i want to add ManyToManyField
    research                = ManyToManyField(ResearchProtocol) #Here i will write for adding the field

class ResearchProtocol(models.Model):

    title = models.CharField(max_length=30)
    description = models.TextField()
    start_date = models.DateField()
    end_date = models.DateField()

    def __unicode__(self):
        return '%s' % self.title

为此我写了sql查询:

CREATE TABLE "visit_visit_research" (
    "id" serial NOT NULL PRIMARY KEY,
    "visit_id" integer NOT NULL REFERENCES "visit_visit" ("id") DEFERRABLE INITIALLY DEFERRED,
    "research_id" integer NOT NULL REFERENCES "www_researchprotocol" ("id") DEFERRABLE INITIALLY DEFERRED,
    UNIQUE ("visit_id", "research_id")
)
;

当我执行此文件时,字段以某种方式创建,但是当我打开vist admin时 并单击以导致更改形式的特定ID它给我以下错误:

http://localhost:8000/admin/visit/visit/20/

Exception Type: DatabaseError at /admin/visit/visit/20/
Exception Value: column visit_visit_research.researchprotocol_id does not exist
LINE 1: ...visit_research" ON ("www_researchprotocol"."id" = "visit_vis...
                                     ^

有人说你需要南方,没有南方就无法完成。这是唯一的解决方案吗?我使用的是Django 1.3.1,Python 2.7.2。

有人可以指导我,我在做什么错吗? 任何帮助将不胜感激。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您已将链接表visit_visit_research及其中的字段research_id调用,而Django则分别期待visit_visit_researchprotocolresearchprotocol_id

答案 1 :(得分:2)

每当我修改表格模型时,我使用南方和这些命令来修改结构,它们总是有效:

python manage.py convert_to_south "your_app"
python manage.py migrate "your_app"

你可以试试这些,它应该可以工作,如果你仍然安装了南方。