Django ManyToManyField没有在admin中保存

时间:2015-07-14 14:51:39

标签: python django

models.py

class Document(models.Model):
document_type_d = models.ForeignKey(DocumentType,
                                    verbose_name="Document Type")

class Section(models.Model):
document_type_s = models.ManyToManyField(DocumentType,
                                         verbose_name="Document Type")

class DocumentType(models.Model):
document_type_dt = models.CharField("Document Type", max_length=240)

当我在管理员中创建一个部分时,它似乎不会保存document_type_s。

在django shell中我可以看到DocumentType正确保存:

>>> dt = DocumentType.objects.all()
>>> for d in dt:
...     print d.document_type_dt
... 
Campus LAN
WAN
Unified Communications

当我查看我得到的章节时:

>>> original_sections = Section.objects.all()
>>> for a in original_sections:
...     print a.document_type_s
... 
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None

当我检查文件时:

>>> d = Document.objects.all()
>>> for e in d:
...     print e.document_type_d
... 
Campus LAN
WAN
Campus LAN

如果我尝试创建一个新部分:

>>> s = Section(document_type_s="Campus LAN", name="Fake", original=True)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 480, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'document_type_s' is an invalid keyword argument for this function

Django似乎在数据库中创建了该字段,查看了我的迁移文件:

migrations.CreateModel(
            name='Section',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('document_type_s', models.ManyToManyField(to='lld.DocumentType', verbose_name=b'Document Type')),
            ]

我不知道造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:1)

您认为这会起作用吗?

Section(document_type_s="Campus LAN", name="Fake", original=True)

document_type_s是一个ManyToMany字段,但是你传入一个字符串值

阅读ManyToMany的文档:
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/

对于要创建的多对多关系,Section实例已经存在(因为在db中m2m关系是一个带有两个外键的额外表)...所以你需要:

dt = DocumentType.objects.get(pk=1)
section = Section.objects.create(name="Fake", original=True)
section.document_type_s.add(dt)