Mastering Django

succeeding·2022년 2월 5일
0

Nigel Geroge"Mastering Django"를 공부하며 하이라이트한 내용을 정리해두었다.

Chapter 4. Models

Installing the Model

  1. Register app to INSTALLED_APPS
    • INSTALLED_APPS tells Django which apps are activated for a given project.
  2. python manage.py check
    • The check command runs the Django system check framework-a set of static checks for validating Django projects.
    • Anytime you think you have problems with your models, run this command.
  3. If your models are valid, python manage.py makemigrations <app>
    • Migrations are how Django stores changes to your mdoels (and thus your database schema)
  4. python manage.py sqlmigrate <app> 0001
    • The sqlmigrate command prints output to the screen so you can see what SQL Djnago would execute if you asked it.
  5. python manage.py migrate <app>
    • The migrate commnad will take your latest migration file and update your database shema automatically

Basic data access

  • To create an object and save it to the database in a single step, use the objects.create() method.

Adding model string representations

  • Make sure any model you define has a __str__() method

Selecting objects

  • The objects attibute is called a manager. The managers take care of all table-level operations on data including data lookup.

Filtering data

  • the __contatins part gets translated by Django into a SQL LIKE statement:
>>> Publisher.objects.filter(name__contains="press")
<QuerySet [<Publisher: Apress>]>

Retrieving single objects

  • The get() method returns only a single object instead of a list.
>>> Publisher.objects.get(name='Apress')
<Publisher: Apress>
  • The DoesNotExist exception is an attribute of the model's class-Publisher.DoesNotExist.
>>> try:
...     p = Publisher.objects.get(name="KOREA")
... except Publisher.DoesNotExist:
...     print("KOREA isn't in the database yet.")
... else:
...     print("KOREA is in the database.")
... 
KOREA isn't in the database yet.

Ordering data

  • To order results, use the order_by() method:
>>> Publisher.objects.order_by("name")
<QuerySet [<Publisher: Apress>, <Publisher: O'Reilly>]>

# multiple arguments
>>> Publisher.objects.order_by("state_province", "address")
<QuerySet [<Publisher: Apress>, <Publisher: O'Reilly>]>

# reverse ordering
>>> Publisher.objects.order_by("-name")
<QuerySet [<Publisher: O'Reilly>, <Publisher: Apress>]>
  • To specify a default ordering in the model, use the Meta class.
class Publisher(models.Model):
    
    class Meta:
        ordering = ['name']
  • The Meta class is used on any model to specify various model-specific options.

Chaining lookups

>>> Publisher.objects.filter(country='U.S.A.').order_by("-name")
<QuerySet [<Publisher: O'Reilly>, <Publisher: Apress>]>

Slicing data

  • Use Python's standard list slicing syntax except for the negative slicing.

Updating multiple objects in one statement

  • Since Django's save() method sets all of the column values, use the update() method on QuerySet objects in order to change only the column you need to change.
>>> Publisher.objects.filter(id=1).update(name='Bpress')
1

>>> Publisher.objects.all().update(country='USA')
2
  • The update() method has a reutrn value-an integer representing how many records changed.

Chapter 5. The Django Admin Site

Adding your models to the admin site

# proejct_dir/app_dir/admin.py

from django.contrib import admin
from .models import Publisher

admin.site.register(Publisher)

Making fields optional

  • Add blank=True
class Author(models.Model):
	email = models.EmailField(blank=True)

Making date and numeric fields optional

  • Use both null=True and blank=True
    1) In SQL, NULL could mean "unknown", or "invalid" ,and a value of NULL is different than an empty string.
    2) This can cause ambiguity and confusion. Django's automatically generated CREATE TABLE statements add an explicit NOT NULL to each column definition.
    3) But there's an exception with database column types that do not accept empty strings as valid values-such as dates, times, and numbers. In this case, NULL is the only the way to specify an empty value.
class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT)
    publication_date = models.DateField(blank=True, null=True)

Customizing edit forms

  • use filter_horizontal for any ManyToManyField that has more than ten items.
class BookAdmin(admin.ModelAdmin):
    filter_horizontal = ('authors',)

Chapter 6. Forms

  • request.META is a Python dictionary containing all avaliable HTTP headers for the given request. When use it, use a try/except clause or the get() method to handle KeyError.
def ua_display(request):
    ua = request.META.get("HTTP_USER_AGENT", "unknown")
    return HttpResponse("Your browser is % s" % ua)


def ua_display(request):
    try:
        ua = request.META["HTTP_USER_AGENT"]
    except KeyError:
        ua = "unknown"
    return HttpResponse("Your browser is % s" % ua)

Chapter 12. Testing in Django

testing은 내용이 많아서 여기서 정리한다.

0개의 댓글