当我尝试在 Ubuntu 终端执行以下代码时遇到问题:
$ python manage.py makemigrations
我需要在我的类中添加一个名为"album"的名为 music 的字段,如下所示:
models.py
文件
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Music(models.Model):
class Meta:
db_table = 'music'
title = models.CharField(max_length=200)
seconds = models.IntegerField()
album = models.ForeignKey('Album', related_name='musics')
def __str__(self):
return self.title
class Album(models.Model):
class Meta:
db_table = 'album'
title = models.CharField(max_length=200)
band = models.ForeignKey('Band', related_name='albuns')
date = models.DateField()
serializers.py
文件
from rest_framework import serializers
from .models import Music, Band, Album, Member
class MusicSerializer(serializers.ModelSerializer):
class Meta:
model = Music
fields = '__all__'
class BandSerializer(serializers.ModelSerializer):
class Meta:
model = Band
fields = '__all__'
我的错误得到:
(music) leonardo.oliveira@dss-skinner:~/django_music/myapi$ python manage.py makemigrations
You are trying to add a non-nullable field 'album' to music 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: 2
这里发生的事情是,它正在尝试在音乐模型中添加专辑字段。根据此字段的定义
album = models.ForeignKey('Album', related_name='musics')
它是一个不可为空的字段。 即时修复将是
album = models.ForeignKey('Album', related_name='musics', null=True)
但是,如果要为此字段添加默认相册,可以通过执行以下操作来添加默认值。
album = models.ForeignKey('Album', related_name='musics', default=Album.objects.first())
但要做到这一点,您应该在数据库中至少存在一个专辑。
执行这些更改后,您运行
python manage.py migrate