问题描述
目前在Django网站上工作,我从我的 models.py
模块导入一个类及其属性到我的视图中.py
模块在我的音乐应用程序。从我所理解的Django使用元类构造模型,所以定义的字段不会最终作为类上的属性。是这个问题,如果是这样我该怎么解决呢?
Currently working on a Django website and I'm having an issue importing a class and its attributes from my models.py
module into my views.py
module within my music app. From what I understand Django uses metaclasses to construct models, so the defined fields don't end up as attributes on the class. Is this the problem and if so how do I solve it?
目录结构:
music
migrations
templates
_init_
admin.py
apps.py
models.py
tests.py
urls.py
views.py
models.py
中的代码是:
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000)
def __str__(self):
return self.album_title + ' - ' + self.artist
views.py
中的代码是:
from django.http import HttpResponse
from .models import Album
from django.template import loader
def index(request):
all_albums = Album.object.all()
template = loader.get_template('music/index.html')
context = {'all albums': all_albums,}
return HttpResponse(template.render(context, request))
def details(request, album_id):
return HttpResponse("<h2> Details for Album id: " + str(album_id) + " </h2>")
strong>错误:
The Error:
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
错误位置:
从.models导入相册
推荐答案
您的 __ str __
方法必须定义为专辑
类,否则self是未定义的
Your __str__
method must be defined into Album
class, otherwise self is undefined
这篇关于ModuleNotFoundError:没有名为“__main __。models”的模块; '__main__'不是一个包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!