class Category(models.Model):
name = models.CharField(u'文章分类', max_length=64)
def __str__(self):
return self.name
class article(models.Model):
title = models.CharField(u'标题', max_length=60)
category = models.ManyToManyField('Category', verbose_name=u'分类', blank=True)
createtime = models.DateTimeField(u'createtime', default=timezone.now)
content = models.TextField(u'内容', blank=True, null=True)
报错如下:
File "C:\Users\lujunhong\Desktop\work\venv\lib\site-packages\django\db\models\options.py", line 614, in get_field
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Category has no field named '文章分类'
请问为什么会提示 没有这个字段呢
1
upczww 2016-10-30 21:56:02 +08:00 via Smartisan T1
给你提个建议,写字段的时候最好都统一一下,写成
关键字参数形式。把文章分类用 verbose_name = "文章分类" 这样写。 |
2
lovebeyondalways OP @upczww 谢谢提醒,可是上面提出的问题是什么原因呢,明明增加了这个字段
|
3
upczww 2016-10-30 22:54:21 +08:00
@lovebeyondalways 你试试这样写:
name = models.CharField(verbose_name = u'文章分类', max_length=64) 估计你直接用位置参数,没用对位置。 |
4
lxy42 2016-10-30 23:38:38 +08:00 via Android
category = models.ManyToManyField('category'...)
这里,去掉引号。 |
5
lxy42 2016-10-30 23:41:24 +08:00 via Android
ManyToManyField 第一个参数是 Model class
|
6
jimmyye 2016-10-31 02:54:54 +08:00
试过了,没有问题
``` class Category(models.Model): name = models.CharField(u'文章分类', max_length=64) def __str__(self): return self.name class article(models.Model): title = models.CharField(u'标题', max_length=60) category = models.ManyToManyField('Category', verbose_name=u'分类', blank=True) createtime = models.DateTimeField(u'createtime', default=timezone.now) content = models.TextField(u'内容', blank=True, null=True) ``` ``` ➜ temp python manage.py makemigrations Migrations for 'core': core/migrations/0001_initial.py: - Create model article - Create model Category - Add field category to article ➜ temp python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, core, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying core.0001_initial... OK Applying sessions.0001_initial... OK ➜ temp ``` |
7
lovebeyondalways OP Category 这个类是我后面加上去的 不知道有没有影响
|
8
jimmyye 2016-10-31 11:22:10 +08:00
@lovebeyondalways 每次修改 /增加 Model 后,都要先`python manage.py makemigrations`生成 migration 文件,然后`python manage.py migrate`应用到数据库。
|
9
lovebeyondalways OP @jimmyye 谢谢啊 这个试用了一样的,最后我把 migrations 文件里内容删了,又把数据库清空,再生成就 OK 了
最原始的办法 |