简体   繁体   中英

How to create an object for a model from the console similar to how Django made the createsuperuser command

I'm trying to create an object from the console but not sure how to set that up. This is my modelManager:

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")

And here is the model:

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

Any help would be much appreciated.

You can go this route using Django's API - checkout the docs

First create a shell:

python manage.py shell

Then you can import your models and do basic CRUD on them.

>>> 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()

Or, alternatively you can try the dbshell route, here's thedocumentation .

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.

You can't use the Django's ORM though, it's pure SQL, so it would be instructions like:

CREATE TABLE user (
  Id Int,
  Name Varchar
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM