如何将模型导入控制台,以便可以从数据库中查找模型的实例?

时间:2019-01-05 20:51:54

标签: python django python-3.x model

我正在使用PyCharm 2018.2和Python 3.7。如何将模型导入控制台,以便可以从数据库中查找模型的实例?我以为这样就可以了

from .models import Article

但是当我在控制台上运行它时,出现以下错误。我不确定它们是什么意思

>>> from .models import Article
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import
    module = self._system_import(name, *args, **kwargs)
KeyError: "'__name__' not in globals"

下面是我的models.py文件...

from django.db import models

# Create your models here.
from datetime import datetime
from django.utils import timezone

class Webpage(models.Model):
   path = models.CharField(max_length=100)

   def __str__(self):
       return self.path

   def create(cls, path):
       Webpage = cls(path=path)
       return Webpage

class Article(models.Model):
    webpage = models.ForeignKey(Webpage, on_delete=models.CASCADE,)
    path = models.CharField(max_length=100)
    url = models.TextField
    time = models.DateTimeField(default=datetime.now)
    votes = models.IntegerField(default=0)
    comments = models.IntegerField(default=0)
    front_page = models.BooleanField(default=False)

    def __str__(self):
        return self.path

    @classmethod
    def create(cls, webpage, path, url, votes, comments):
        article = cls(webpage=webpage,path=path,url=url,votes=votes,comments=comments)
        return article

2 个答案:

答案 0 :(得分:1)

尝试使用命令python manage.py shell,然后包括您的模型类。

在此处进行了全部解释:https://tutorial.djangogirls.org/en/django_orm/

答案 1 :(得分:1)

尝试在您的import语句中输入应用名称:

from <name of your app>.models import Article

Django shell在您的项目目录中运行,但是models.py在您的应用程序目录中。