如何在 .py 文件中创建模型实例?

射频

因此,当我使用 CLI 创建模型实例时,它可以工作。

该模型:

class Post(models.Model):
    title = models.CharField(max_length=100)
    cover = models.ImageField(upload_to='images/')
    description = models.TextField(blank=True)

    def __str__(self):
        return self.title

然后我做了:

$ python manage.py shell
>>>from blog.models import Post
>>>filename = 'images/s.png'
>>>Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing')

它奏效了,它出现在我展示这些模型的页面上。

但是,当我使用相同的代码并将其放入文件组合_同步.py 时,它不起作用。

from blog.models import Post

filename = 'images/s.png'
Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing')

我收到此错误:

Traceback (most recent call last):
  File "portolio_sync.py", line 1, in <module>
    from models import Post
  File "/Users/rfrigo/dev/ryanfrigo/blog/models.py", line 4, in <module>
    class Post(models.Model):
  File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config
    self.check_apps_ready()
  File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready
    settings.INSTALLED_APPS
  File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
    self._setup(name)
  File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

我该如何解决这个问题,并在 .py 文件中创建一个模型实例?(因为我需要遍历一堆文件名)。

谢谢你的帮助!!

雷扎·GH

你必须在 shell 中运行这个脚本

要在 shell 中执行此脚本,请打开终端并执行以下操作:

python manage.py shell < myscriptname.py

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章