更新模型中的新字段

4 投票
1 回答
5218 浏览
提问于 2025-04-28 00:29

我正在尝试更新数据库中关于我的“卡片”模型的新字段,这个模型之前已经有了一些字段,但我遇到了一个问题,阻碍了我这个过程:

当我运行 ./manage.py syncdb 时,出现了这个信息:

Your models have changes that are not yet reflected in a migration, and so won't be applied.
  Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

所以我运行了 makemigrations 命令,但是……

You are trying to add a non-nullable field 'imagen' to card without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py

我选择了第二个选项,自己添加要求,实际上我现在有这个:

models.py:

from django.db import models

class subscriber(models.Model):
    nombre = models.CharField(max_length=200)
    apellidos = models.CharField(max_length=200)
    status = models.BooleanField(default=True)

    def __unicode__(self):
        nombreCompleto = "%s %s"%(self.nombre,self.apellidos)
        return nombreCompleto

def url(self,filename):
    ruta = "MultimediaData/Card/%s/%s"%(self.nombre,str(filename))
    return ruta

class card(models.Model):

    nombre = models.CharField(max_length=100)
    descripcion = models.TextField(max_length=300)
    status = models.BooleanField(default=True)
    imagen = models.ImageField(upload_to=url)
    precio = models.DecimalField(max_digits=6,decimal_places=2)
    stock = models.IntegerField()

    def __unicode__(self):
        return self.nombre

如果我按照信息所说修改“Imagen”字段,我会这样做:

imagen = models.ImageField(upload_to=url, default='')

但是在对“imagen”字段做了同样的修改后,还是出现了同样的信息:

You are trying to add a non-nullable field 'precio' to card without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:

最后还有这个:

You are trying to add a non-nullable field 'stock' to card without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:

如果我修改了所有这些字段,我最终可以运行 ./manage.py makemigrations:

Migrations for 'synopticup':
  0002_auto_20141016_2004.py:
    - Add field imagen to card
    - Add field precio to card
    - Add field stock to card

但是当我运行 ./manage.py syncdb 时,我得到了这个错误:

django.core.exceptions.ValidationError: [u"'' value must be a decimal number."]

我的过程哪里出错了?我更希望一切都保持原样:

class card(models.Model):

    nombre = models.CharField(max_length=100)
    descripcion = models.TextField(max_length=300)
    status = models.BooleanField(default=True)
    imagen = models.ImageField(upload_to=url)
    precio = models.DecimalField(max_digits=6,decimal_places=2)
    stock = models.IntegerField()

提前为我冗长的问题道歉,如果我遗漏了什么。

谢谢!!

暂无标签

1 个回答

4

一个DecimalField的默认值应该是一个Decimal对象。

from decimal import Decimal

class card(models.Model):
    # ...
    imagen = models.ImageField(upload_to=url, default='')
    precio = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal(0))
    stock = models.IntegerField(default=0)

撰写回答