python - 如何从控制台为模型创建对象,类似于 Django 创建 createsuperuser 命令的方式

标签 python django python-3.x command-line

我正在尝试从控制台创建一个对象,但不确定如何设置它。 这是我的模型管理器:

class MajorManager(models.Manager):

def __str__(self):
    return self.name 

def createMajor(self, name):
    try:
        name = name.lower()
        major = self.create(name=name)    
    except IntegrityError:
        print("This major has already been created")

这是模型:

class Majors(models.Model):
name = models.CharField(max_length=30, unique=True)
objects = MajorManager()

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用 Django 的 API 走这条路 - checkout the docs

首先创建一个shell:

python manage.py shell

然后您可以导入您的模型并对它们执行基本的CRUD

>>> from polls.models import Choice, Question  # Import the model classes we just wrote.

# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>

# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# Save the object into the database. You have to call save() explicitly.
>>> q.save()

或者,您也可以尝试 dbshel​​l 路由,这里是 documentation .

This command assumes the programs are on your PATH so that a simple call to the program name (psql, mysql, sqlite3, sqlplus) will find the program in the right place. There’s no way to specify the location of the program manually.

虽然你不能使用 Django 的 ORM,它是纯 SQL,所以它会是这样的指令:

CREATE TABLE user (
  Id Int,
  Name Varchar
);

关于python - 如何从控制台为模型创建对象,类似于 Django 创建 createsuperuser 命令的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53659801/

相关文章:

python - import_meta_graph 失败,数据丢失 : not an sstable (bad magic number)

Python 3.3 : printing special symbols like ♥ and ❦ when running through command line

python - Pandas 列的累积总和,直到达到最大值,并平均相邻行

python - 保留出现 N 次或更多次的字符串

django - 如何在开发下一个版本的同时运行一个版本的 Web 应用程序?

python - 如何在 Windows 上获取总磁盘大小?

python - 使用 python 和 DBSCAN 聚类高维数据

javascript - 使用ajax提交表单

django - 基于 get_initial() 的 CBV CreateView 限制 ForeignKey

Python sympy.Plot - OverflowError : int too large to convert to float