【问题标题】:Populate existing Django rows, But there are no rows填充现有的 Django 行,但没有行
【发布时间】:2018-11-15 19:37:48
【问题描述】:

我正在尝试迁移我的模型:

class EntitiesModel(models.Model):
    entity_id = models.TextField()
    entity_name = models.TextField()
    entity_type = models.TextField(choices=ENTITY_TYPES)

    #generic key to sources or targets
    content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

我得到了错误:

您正在尝试在没有默认值的情况下将不可为空的字段“实体名称”添加到实体模型;我们不能这样做(数据库需要一些东西来填充现有的行)。

但是当我检查数据库时:

>>>from forward import models
>>>models.EntitiesModel.objects.all()
<QuerySet []>

你有什么线索会导致这个问题吗?

【问题讨论】:

  • 我的回答中描述了所有可用的选项,因此您可以选择适合您的模型结构的选项

标签: django database django-models migration


【解决方案1】:

这些字段不能留空,您应该添加blank=True,以便数据库接受它们可以具有空值。

entity_id = models.TextField(blank=True)
entity_name = models.TextField(blank=True)
entity_type = models.TextField(blank=True,choices=ENTITY_TYPES)

以防万一,您不希望它们为空。 基本上,您的所有字段都是必需的,这意味着在创建新实例时,您需要全部填写。

EntitiesModel.objects.create(
   entity_id = "Value",
   entity_name = "name",
   entity_type = 'type',
   content_object = 'instance',
)

根据您的回溯:

您正在尝试向实体添加一个不可为空的字段“entity_name”

您正在尝试在 python 中添加可能为 null None 的值,Django 将引发错误。所以你有参数null=True 允许一个字段接受一个可以为空的值。

entity_id = models.TextField(blank=True,null=True)
entity_name = models.TextField(blank=True,null=True)
entity_type = models.TextField(blank=True,choices=ENTITY_TYPES,null=True)

如果您不想存储可为空的值,请在创建实例之前确保该值不是null 或不是None

【讨论】:

  • 但是如果我不想让它们为空怎么办?
  • 我不是在创造价值,我只是在尝试进行迁移。你是对的,所有值都应该是必需的。基于回溯“(数据库需要一些东西来填充现有的行)。”似乎问题是已经创建的实体,但是“”显示数据库是空的。
  • 在进行迁移之前,EntitiesModel 有值吗?
  • 没有实体模型为空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 2021-10-27
  • 2017-04-12
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
相关资源
最近更新 更多