我在ForeignKey中更改了ManyToManyField关系,但现在不起作用

时间:2016-05-04 10:53:21

标签: python django python-3.x django-models

我是Django的新手,我遇到了这个问题:我想创建一个简单的网站,我在其中显示和处理视图对象Album和Artist。我改变了关系

class Album(models.Model):
    ...
    songs_of_album = models.ManyToManyField('Song')

class Song(models.Model):
     name = models.CharField(max_length=150)

在我当前的models.py文件中

from django.db import models
from django.utils import timezone

class Album(models.Model):
    name = models.CharField(max_length=150,default='')
    artist = models.CharField(max_length=150,null=False,blank=False)
    year = models.IntegerField(default=timezone.now().year)
    genre = models.ForeignKey('Genre',blank=False)
    vote = models.IntegerField(blank=True,null=True)
    def __str__(self):
        return self.name

class Song(models.Model):
    name = models.CharField(max_length=150,null=False,blank=False)
    album_name = models.ForeignKey('Album')
    artist = models.ForeignKey('Artist')
    def __str__(self):
    return self.name

class Artist(models.Model):
    name = models.CharField(max_length=150,primary_key=True)
    def __str__(self):
       return self.name

class Genre(models.Model):
    name = models.CharField(max_length=150,primary_key=True)
    def __str__(self):
        return self.name

我想知道两件事:

  • 如果我的models.py写得正确,并且类和专辑艺术家之间存在关系
  • 现在,当我运行命令python manage.py makemigrations时,我发现此错误You are trying to add a non-nullable field 'id' to album 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) 2) Quit, and let me add a default in models.py Select an option:

我看过很多类似的帖子,但他们无法找到解决方案。 我希望你能帮助我。谢谢

1 个答案:

答案 0 :(得分:0)

您将m2m关系更改为one2many,一切正常,但您需要更改相关的数据库表,并且必须将数据库迁移到新样式,如果有null=True的数据库album_name的任何数据Song类的属性,如果你的db是空的,删除除migrations文件之外的应用程序的__init__.py文件夹中的所有文件,然后运行以下两个命令:

python manage.py makemigrations

然后:

python manage.py migrate