python-3.x - 如何将scrapy数据中的数据发送到django模型?

标签 python-3.x django scrapy

是否可以在 django 中使用 scrapy 创建新产品?

每当我运行 scrapy.py 时,我都会收到以下错误:

raise ImproperlyConfigured(
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.

我的应用程序模型文件

from django.db import models

# Create your models here.

class Product(models.Model):
    name = models.CharField(max_length=50)
    age =  models.IntegerField()
    content =  models.TextField(max_length=400)
    def __str__(self):
        return self.name

scrapy.py文件

from models import Product

Product.objects.create(name='BMW', age=25, content='cool car')

最佳答案

是的,当然可以,您只需导入 django 并配置 DJANGO_SETTINGS_MODULE 变量即可:

import django
import os

# Configure settings for project
# Need to run this before calling models from application!
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings') # Replace app_name with your application name.

# Import settings
django.setup()

# Import the models now
from app_name.models import Product

# Use the imported model
product = Product.objects.create(...)

更多信息on this post

关于python-3.x - 如何将scrapy数据中的数据发送到django模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70130691/

相关文章:

python-3.x - Python - 具有多个时区的 Pandas 日期时间列

python-3.x - 使用 setuptools(setup.py) 在主模块之外添加文件夹和子文件夹

python - Python 中非奇数的舍入错误?

python - 如何在 Google App Engine 上的 django 中避免 NotImplementedError "Only tempfile.TemporaryFile is available for use"?

python - 无法使用类名包含尾随空格的 Scrapy 提取数据

python - 如何获取Scrapy 0.12版本?

python - 字符串到 unix 文件名的可逆编码

python - Django:如何在 1.8 中转储数据库?

python - 关键字 arg 之后的 Django SSLRedirect 非关键字 arg

python - 如何设置 scrapy 蜘蛛 ReturnsContract 的上限