在Djnago中进行迁移不会创建ForeignKey和OneToOneFields,而是在创建模型后添加它们。无法迁移

时间:2019-02-03 17:11:18

标签: django django-models django-migrations

预先感谢您抽出时间来研究我的问题。 我正在使用以下方法开发小型项目管理应用程序: 带有Django 2.1.5的Python 3.6

为模型进行迁移时遇到一些问题。

基本上,我正在构建一个主要的项目模型,与此相关的是我将其他活动链接到该模型。 在进行迁移时,我必须在终端中输入以下内容:

注意: 对于“ project_creator”迁移,在创建模型后会添加OneToOneFields和ForeignKeys

(env) $ python manage.py makemigrations

Migrations for 'authentication':
  authentication/migrations/0001_initial.py
    - Create model User
    - Create model Profile
    - Create model Roles
Migrations for 'project_creator':
  project_creator/migrations/0001_initial.py
    - Create model ProjectBudgetModel
    - Create model ProjectDatesModel
    - Create model ProjectDescriptionModel
    - Create model ProjectMember
    - Create model ProjectModel
    - Create model ProjectProblemsToDescriptionModel
    - Create model ProjectTasksToDescriptionModel
    - Add field project to projectmember #         
    - Add field project_member to projectmember 
    - Add field project to projectdescriptionmodel
    - Add field updated_by to projectdescriptionmodel
    - Add field project to projectdatesmodel
    - Add field updated_by to projectdatesmodel
    - Add field project to projectbudgetmodel
    - Add field responsible to projectbudgetmodel
    - Add field updated_by to projectbudgetmodel

当我迁移到PostgreSQL数据库时,出现ValueError:

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, authentication, authtoken, contenttypes, guardian, projects, sessions, token_blacklist
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... 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 auth.0009_alter_user_last_name_max_length... OK
  Applying authentication.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying authtoken.0001_initial... OK
  Applying authtoken.0002_auto_20160226_1747... OK
  Applying guardian.0001_initial... OK
  Applying projects.0001_initial...Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 203, in handle
    fake_initial=fake_initial,
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
    field,
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 421, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 168, in column_sql
    default_value = self.effective_default(field)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 239, in effective_default
    return field.get_db_prep_save(default, self.connection)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/models/fields/related.py", line 937, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 790, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 956, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/Users/radoo/Projects/006_Projects/MrProject/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 965, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'Not Defined'

这是我的代码的一部分。基本上,我创建一个项目,然后通过OneToOneFields或ForeignKeys将其他模型链接到该项目。

models.py

from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _

from guardian.shortcuts import assign_perm

User = get_user_model()


class ProjectModel( models.Model ):
    TYPE_CHOICES = (
        ("A", "A"),
        ("B", "B"),
        ("C", "C"),
        ("O", "O")
        )

    DEPARTMENT = (
        ("R&D", "Research and Development"),
        ("OPERATIONS", "Production and operations"),
        ("SCM", "Supply chain management"),
        ("PGM", "Program Management"),
        ("SALES", "Sales Management"),
        ("STRATEGIC", "Strategic"),
        ("IT", "Information Technology"),
        ("OTHER", "Other"),
        )

    REGIONS = (
        ("EU", "Europe"),
        ("ASIA", "Asia"),
        ("NORTH_AMERICA", "North America"),
        ("SOUTH_AMERICA", "Middle East and Africa"),
        ("MEAT", "Middle East and Africa"),
        ("OTHER", "Other Region"),
        )

    id = models.AutoField( _( "ID" ), primary_key=True, unique=True )
    title = models.CharField( _( "Project Title" ), max_length=100, unique=True, blank=False, null=False )
    slug = models.SlugField( unique=True )
    project_number = models.CharField( _( "Project Number" ), max_length=50, unique=True )
    project_type = models.CharField( _( "Project Type" ), max_length=2, choices=TYPE_CHOICES, default="O" )
    project_department = models.CharField( _( "Department" ), max_length=50, choices=DEPARTMENT, default="OTHER" )
    project_region = models.CharField( _( "Region" ), max_length=50, choices=REGIONS, default="OTHER" )
    created_at = models.DateTimeField( _( "Created at" ), auto_now_add=True )
    updated_at = models.DateTimeField( _( "Updated at" ), auto_now=True )
    created_by = models.ForeignKey( User, related_name="projects_created", null=True, on_delete=models.DO_NOTHING )
    updated_by = models.ForeignKey( User, related_name="projects_update", null=True, blank=True,
                                    on_delete=models.DO_NOTHING )
    is_approved = models.BooleanField( default=False )
    approved_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.DO_NOTHING )

    class Meta:
        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_project', "View Project"),
            )
        verbose_name = _( 'project' )
        verbose_name_plural = _( 'projects' )
        db_table = "project_model"

    def save(self, *args, **kwargs):
        top = ProjectModel.objects.all().count()
        series = "{:0>6}".format( top )
        self.project_number = "%s-%s-%s"%(str( self.project_type ), str( self.project_department ), str( series ))
        self.slug = slugify( self.title )
        super().save( *args, **kwargs )

    def __str__(self):
        return "%s / %s"%(str( self.project_number ), str( self.title ))

class ProjectDescriptionModel( models.Model ):
    project = models.OneToOneField(
            ProjectModel, on_delete=models.CASCADE
            )
    updated_by = models.ForeignKey(
            User, on_delete=models.DO_NOTHING )
    updated_at = models.DateTimeField( _( "Updated at" ), auto_now=True )

    current_situation = models.TextField( _( "Current Situation" ), blank=True, default="No situation described" )
    project_scope = models.TextField( _( "Project Scope" ), blank=True, default="No scope described" )
    not_project_scope = models.TextField( _( "Not in Project Scope" ), blank=True, default="No scope described" )
    benefit = models.TextField( _( "Benefit" ), blank=True, default="No benefit described" )
    target = models.TextField( _( "Target" ), blank=True, default="No target described" )
    slug = models.SlugField( unique=True )

    def save(self, *args, **kwargs):
        self.slug = self.project.slug
        super().save( *args, **kwargs )

    class Meta:
        verbose_name = "description"
        verbose_name_plural = "description"

        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_description', "View description"),
            )
        db_table = "project_description"

    def __str__(self):
        return "%s-%s"%("Description for project: ", str( self.project.title ))


class ProjectDatesModel( models.Model ):
    project = models.ForeignKey(
            ProjectModel, on_delete=models.CASCADE
            )
    description = models.CharField( _( "Activity description" ), max_length=255, default="A short description",
                                    blank=True, null=False )
    started_date = models.DateField( _( "Started date" ), auto_now_add=True )
    due_date = models.DateField( _( "Planned date" ), null=True, blank=True )
    done_date = models.DateField( _( "Done date" ), null=True, blank=True )
    delayed = models.BooleanField( _( "Delayed" ), default=False )
    ongoing = models.BooleanField( _( "On going" ), default=False )
    done = models.BooleanField( _( "Done" ), default=False )
    updated_by = models.ForeignKey(
            User, on_delete=models.DO_NOTHING, related_name="date_member" )

    def save(self, *args, **kwargs):
        super().save( *args, **kwargs )

    class Meta:
        verbose_name = "date"
        verbose_name_plural = "dates"

        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_date', "View Date"),
            )
        db_table = "project_dates"

    def __str__(self):
        return "%s-%s"%(str( self.project.project_number ), str( self.description ))

class ProjectBudgetModel( models.Model ):
    project = models.OneToOneField(
            ProjectModel, on_delete=models.CASCADE
            )
    updated_by = models.ForeignKey(
            User, on_delete=models.DO_NOTHING )
    updated_at = models.DateTimeField( _( "Updated at" ), auto_now=True )
    cost_center = models.CharField( _( "Cost Center" ), max_length=20, null=False, blank=False, default="Not Defined" )
    responsible = models.ForeignKey(
            User, on_delete=models.DO_NOTHING, related_name="responsible_budget", blank=True, default="Not Defined" )
    cost = models.FloatField( _( "Project Costs in Eur" ), null=True )
    investments = models.FloatField( _( "Project Investment in Eur" ), null=True )
    budget_cost = models.BooleanField( _( "Budgeted Costs" ), default=False )
    budget_invest = models.BooleanField( _( "Budgeted Investments" ), default=False )
    slug = models.SlugField( unique=True )

    def save(self, *args, **kwargs):
        self.slug = self.project.slug
        super().save( *args, **kwargs )

    class Meta:
        verbose_name = "budget"
        verbose_name_plural = "budgets"

        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_budget', "View Budget"),
            )
        db_table = "project_budget"

    def __str__(self):
        return "%s-%s"%("Budget for project: ", str( self.project.project_number ))


class ProjectMember( models.Model ):
    project_member = models.ForeignKey(
            User, on_delete=models.DO_NOTHING )
    project = models.ForeignKey(
            ProjectModel, on_delete=models.CASCADE )
    is_project_manager = models.BooleanField( default=False )
    is_sponsor = models.BooleanField( default=False )
    is_team_member = models.BooleanField( default=False )
    is_collaborator = models.BooleanField( default=False )
    is_controller = models.BooleanField( default=False )
    is_steering = models.BooleanField( default=False )
    is_initiator = models.BooleanField( default=False )
    department = models.CharField( _( "Department" ), max_length=50, default="No Department set" )
    requires_signature = models.BooleanField( default=False )

    # def save(self, *args, **kwargs):
    #     # self.is_team_member = True
    #     super().save( *args, **kwargs )

    class Meta:
        verbose_name = _( 'member' )
        verbose_name_plural = _( 'members' )

        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_member', "View Team"),
            )
        db_table = "project_member"

    def __str__(self):
        return "%s / %s"%(str( self.project_member.email ), str( self.project.project_number ))


class ProjectProblemsToDescriptionModel( models.Model ):
    project_description = models.ForeignKey(
            ProjectDescriptionModel, on_delete=models.CASCADE
            )
    updated_by = models.ForeignKey(
            User, on_delete=models.DO_NOTHING )
    updated_at = models.DateTimeField( _( "Updated at" ), auto_now=True )

    problem = models.CharField( _( "Problems" ), default="State a problem", max_length=50, blank=False, null=False )

    class Meta:
        verbose_name = "problem"
        verbose_name_plural = "problems"

        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_problem', "View problem"),
            )
        db_table = "project_problem_to_description"

    def __str__(self):
        return "%s-%s"%("Problem for project: ", str( self.project_description.project.project_number ))


class ProjectTasksToDescriptionModel( models.Model ):
    project_description = models.ForeignKey(
            ProjectDescriptionModel, on_delete=models.CASCADE
            )
    updated_by = models.ForeignKey(
            User, on_delete=models.DO_NOTHING )
    updated_at = models.DateTimeField( _( "Updated at" ), auto_now=True )

    task = models.CharField( _( "Task" ), default="State a task", max_length=50, blank=False, null=False )

    class Meta:
        verbose_name = "task"
        verbose_name_plural = "tasks"

        default_permissions = ('add', 'change', 'delete')
        permissions = (
            ('view_task', "View task"),
            )
        db_table = "project_task_to_description"

    def __str__(self):
        return "%s-%s"%("Task for project: ", str( self.project_description.project.project_number ))

我尝试过的方法: 1)启动一个新应用=>相同的问题;

2)首先迁移ProjectModel(基础模型),然后再迁移其他模型=>可行,但未迁移权限模型。

3)一次迁移一个模型=>可行,但适得其反。尤其是当我有序列化和视图等时。

1 个答案:

答案 0 :(得分:1)

该错误表明您正在尝试将字符串“未定义”保存在整数字段中。因此,只需检查模型的所有整数字段(包括ForeignKey字段),您就可以将“未定义”设置为default值。

如果这是一个可以为空(ForeignKey)的null=True字段,则不要设置默认值,因为默认值将为null。