How Django Works? - 02

Haebin Ethan Jeong·2020년 6월 7일
0

Django

목록 보기
2/4

Database Setup

settings.py

TIME_ZONE

  • You can change your time zone
  • 'Asia/Seoul'

INSTALLED_APPS

  • A list of strings designating all applications that are enabled in this Django installation. Each string should be a dotted Python path to:
    - an application configuration class (preferred), or
    - a package containing an application.

migrate

  • It synchronizes the database state with the current set of models and migrations
  • migrate command looks at the INSTALLED_APPS and creates any necessary database tables.

Model

- A model is the single, definitive source of truth about your data. It contains the essential fields and behaviors of the data you're storing.

polls/models.py

  • In poll app, we create two models: Question and Choice.

  • A Question has a question and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each Choice is associated with a Question.

  • Here, each model is represented by a class that subclasses django.db.models.Model

  • CharField represents character field

  • DateTimeField represents datetime field.

  • question_text and pub_date is a machine-friendly format.

  • ForeignKey is a field(with two arguments) in one table that refers to the primary key in another table.

  • ForeignKey tells each Choice is related to a single Question.

  • on_delete=models.CASCADE will detele the object containing the ForeignKey.

Activating Models

That small bit of model code above gives Django a lot of information. Django can create a database schema for this app and create a python database-access API.

To include the app in our project, we need to add 'polls.apps.PollsConfig' to "INSTALLED_APPS in mysite/settings.py

  • And then, do $ python manage.py makemigrations polls
  • Migrations are how Django stores changes to your models (and thus your database schema(.
  • makemigrations: tells Django that you want to save the change via migration. It creates the SQL commands for preinstalled apps.
  • The migrate command takes all the migrations that haven't been applied and runs them against your database - synchronize the changes I made to my models with the schema in the database

Playing with the API

  • After you type $ python manage.py shell to your terminal, you'll be able to enter the Python shell.

EXPLORING THE DATABASE

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

# Now it has an ID.
>>> q.id
1

# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()

# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

__str__() method

  • __str__() method is called whenever you call str() on an object. This displays an object in the Django admin site and and as the value inserted into a template when it displays an object.

UPGRADING THE DATABASE

>>> from polls.models import Choice, Question

# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>

# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>

# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True

# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>

# Create three choices.
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Question objects.
>>> c.question
<Question: What's up?>

# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
>>> Choice.objects.filter(question__pub_date__year=current_year)
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

# Let's delete one of the choices. Use delete() for that.
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

str method

  • In polls/models.py, you need to add str methods to your models.
  • The __str__ method is used to display an object in the Django admin site and return a nice, human-readable representation of the model from the str() method.

Importing datetime

  • Python's datetime.datetime objects can store time zone information.
  • A 'timedelta' object represents a duration (the difference) between two times.
  • timezone.now() = current time

Introducing the Django Admin

  • $ python manage.py createsuperuser will create the admin. Then, you enter the user name, email, and password.
  • We need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:
profile
I'm a Junior studying Economics and Computer Science at Vanderbilt University.

0개의 댓글