在模型.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)
当我在管理中创建一个节时,它似乎没有保存文档类型
在django shell中,我可以看到DocumentType正在正确保存:
^{pr2}$当我检查这些部分时,我得到:
>>> 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')),
]
我不知道是什么引起的?在
你觉得这会怎么样?在
document_type_s
是一个manytomy字段,但您正在传递一个字符串值多次阅读文档:
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/
要创建多对多关系,
^{pr2}$Section
实例必须已经存在(因为在数据库中,m2m关系是一个带有两个外键的额外表)。。。所以你需要:因此,据我所知,Section类中的ManyToManyField实际上并没有在Section数据库表中保存任何DocumentType数据,而是保存了与DocumentType的关系。 因此,如果我想访问节的document_类型,就必须通过DocumentType对象查找section对象,反之亦然。在
例如:
或者:
^{pr2}$或者:
尽管如此:
^{4}$引发
ValueError: invalid literal for int() with base 10: 'WAN'
,因为节文档类型m2m字段下没有数据,只有关系。所以情况仍然如此:更多信息here。在
相关问题 更多 >
编程相关推荐