gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:14:22 25 4
gpt4 key购买 nike

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

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 simplecall to the program name (psql, mysql, sqlite3, sqlplus) will find theprogram in the right place. There’s no way to specify the location ofthe program manually.

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

CREATE TABLE user (
Id Int,
Name Varchar
);

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com