Django “NameError: name 'Album' not define

2019-09-20 13:18发布

I am trying to run see and manipulate a simple django database but the error from the Django Shell is saying one of my models isn't defined.

Most of the questions with errors similar to mine are due to people referencing a model before declaring it. However, I'm not referencing any other model in Album.

models.py

from __future__ import unicode_literals

from django.db import models


class Album(models.Model):
    artist = models.CharField(max_length=250)
    title = models.CharField(max_length=500)
    genre = models.CharField(max_length=100)
    logo = models.CharField(max_length=1000)


class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    title = models.CharField(max_length=250)

The error I am getting: NameError: name 'Album' is not defined

Any idea what could the the cause of this error?

For reference, I'm following thenewboston's django tutorial here.

3条回答
欢心
2楼-- · 2019-09-20 13:49

You can also write album in quotes and see like this

album = models.ForeignKey("Album", on_delete=models.CASCADE)

This worked for me!

查看更多
3楼-- · 2019-09-20 13:53

When you open your shell, it is just a python shell without anything from your app imported.

You should import your models first:

from your_app_name.models import Album

If you don't want to import your models every time, use django-extensions which will load them for you. Use shell_plus command:

python manage.py shell_plus

Hope it helps

查看更多
太酷不给撩
4楼-- · 2019-09-20 13:59

You should try like this--

class Song(models.Model):
album = models.ForeignKey('app_name.Album', on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
title = models.CharField(max_length=250)
查看更多
登录 后发表回答