您正试图将不可为空的字段“id”添加到mod中

2024-10-02 20:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试开发一个web应用程序,提供在django上创建一个迷你游戏联盟。在创建数据库时,我得到以下错误:

You are trying to add a non-nullable field 'id' to juego without a default; we can't do that (the database needs something to populate existing rows).

这是我在文件models.py上的类Juego

class Juego(models.Model):
   nombre_juego = models.CharField(max_length=100)
   record = models.DecimalField(max_digits=10000000, decimal_places=3)
   fecha_inicio = models.DateTimeField(default=timezone.now)
   fecha_fin = models.DateTimeField(default=timezone.now)
   enlace = models.CharField(max_length=1000)

在上次迁移之后,我将以下类添加到模型中:

^{pr2}$

Tags: todjangoweb应用程序defaultmodelslengthnow
1条回答
网友
1楼 · 发布于 2024-10-02 20:29:58

你现在的代码没有问题。我刚做了一个django项目并运行了它:

型号:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

# Create your models here.
class Juego(models.Model):
   nombre_juego = models.CharField(max_length=100)
   record = models.DecimalField(max_digits=10000000, decimal_places=3)
   fecha_inicio = models.DateTimeField(default=timezone.now)
   fecha_fin = models.DateTimeField(default=timezone.now)
   enlace = models.CharField(max_length=1000)

class Juegan(models.Model):
    user = models.ManyToManyField(User)
    nombre_juego = models.ManyToManyField(Juego)
    puntuacion = models.DecimalField(max_digits=10000000, decimal_places=3)

迁移1:

^{pr2}$

迁移2:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('jugando', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Juegan',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('puntuacion', models.DecimalField(max_digits=10000000, decimal_places=3)),
                ('nombre_juego', models.ManyToManyField(to='jugando.Juego')),
                ('user', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]

运行这个:

brendan@brendan-UX305FA:~/Devel/test/juego$ python manage.py makemigrations
Migrations for 'jugando':
  0002_juegan.py:
    - Create model Juegan
brendan@brendan-UX305FA:~/Devel/test/juego$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, jugando, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying jugando.0002_juegan... OK

问题一定是在你展示的片段之外的某个地方:可能是数据完整性问题。如果你还没有任何重要的数据,你应该考虑重新建立一个新的数据库。在

相关问题 更多 >