【问题标题】:How can i set a default value to an OneToOneField relationship which it's automatically generated?如何将默认值设置为自动生成的 OneToOneField 关系?
【发布时间】:2019-12-12 18:03:26
【问题描述】:

我有两个他们喜欢的模型类:


from django.db import models
from django.urls import reverse

class Place(models.Model):
    address = models.CharField(max_length=80)


class Author(Place):
    name = models.CharField(max_length=50)

但是当我想执行 makemigartions 时,django 会在下面显示错误:

You are trying to add a non-nullable field 'place_ptr' to author 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 with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 

我在 Author 表中有一些数据,但我不想删除这些数据。

有没有人可以帮帮我?

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您可以删除特定应用的旧迁移文件或整个迁移文件夹,然后执行python manage.py makemigrations <app_name>
    如果这不是您想要的解决方案,那么you can find the solution here.

    【讨论】:

    • 它会执行所有迁移过程,但似乎存在问题,我的数据库中未生成位置表。在迁移日志中显示:book/migrations/0001_initial.py - 创建模型位置 - 创建模型作者
    • 在数据库表名中将采用<app_name>_<model_name>的形式。你看那个吗?
    • 不,我没有找到。 aslo 我尝试通过执行 Place.objects.all() 从数据库中获取 Place 数据模型,但它向我显示 django.db.utils.OperationalError: no such table: book_place
    猜你喜欢
    • 2017-07-24
    • 1970-01-01
    • 2019-10-06
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多