Skip to main content
 首页 » 编程设计

python之Django 只从模型中添加一个字段

2024年10月24日33grandyang

当我编辑模型以包含更多字段并进行迁移时,Django 不会在不删除旧字段的情况下添加新字段。

这是模型

class Testimonial(models.Model): 
    name = models.CharField(max_length=20, null=True), 
    quote = models.CharField(max_length=255, null=True), 
    test = models.CharField(max_length=20, null=True) 

这是我在终端中得到的

“推荐”的迁移:
0004_auto_20160212_1537.py:
- 从推荐中删除字段引用
- 将现场测试添加到推​​荐

这是最近的迁移

from __future__ import unicode_literals 
 
from django.db import migrations, models 
 
 
class Migration(migrations.Migration): 
 
    dependencies = [ 
        ('testimonials', '0003_auto_20160212_1536'), 
    ] 
 
    operations = [ 
        migrations.RemoveField( 
            model_name='testimonial', 
            name='quote', 
        ), 
        migrations.AddField( 
            model_name='testimonial', 
            name='test', 
            field=models.CharField(max_length=20, null=True), 
        ), 
    ] 

请您参考如下方法:

我很确定问题是由尾随字段的逗号引起的,在 python 中,这表明您正在创建一个元组,它将把下一行视为该元组对象的延续,你需要删除它们

class Testimonial(models.Model): 
    name = models.CharField(max_length=20, null=True), 
    quote = models.CharField(max_length=255, null=True), 
    test = models.CharField(max_length=20, null=True) 

应该是

class Testimonial(models.Model): 
    name = models.CharField(max_length=20, null=True) 
    quote = models.CharField(max_length=255, null=True) 
    test = models.CharField(max_length=20, null=True)