如何在 .py 文件中创建模型实例?
Posted
技术标签:
【中文标题】如何在 .py 文件中创建模型实例?【英文标题】:How can I create model instances in a .py file? 【发布时间】:2021-03-11 04:24:52 【问题描述】:所以当我使用 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')
它起作用了,它出现在我展示这些模型的页面上。
但是,当我使用相同的代码并将其放入文件portfolio_sync.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 文件中创建模型实例? (因为我需要遍历一堆文件名)。
感谢您的帮助!!
【问题讨论】:
这能回答你的问题吗? ***.com/questions/26082128/… 我想你想做的就是这个***.com/questions/16853649/… 【参考方案1】:你必须在 shell 中运行这个脚本
要在 shell 中执行此脚本,请打开终端并执行以下操作:
python manage.py shell < myscriptname.py
【讨论】:
以上是关于如何在 .py 文件中创建模型实例?的主要内容,如果未能解决你的问题,请参考以下文章