models.py
https://docs.djangoproject.com/ko/3.2/topics/db/models/
https://brunch.co.kr/magazine/django-doc
간단한 구조
- models.py
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
- sql문
CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);
- 일반적인 모델
from django.db import models
class MyModelName(models.Model):
"""A typical class defining a model, derived from the Model class."""
# Fields
my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
...
# Metadata
class Meta:
ordering = ['-my_field_name']
# Methods
def get_absolute_url(self):
"""Returns the url to access a particular instance of MyModelName."""
return reverse('model-detail-view', args=[str(self.id)])
def __str__(self):
"""String for representing the MyModelName object (in Admin site etc.)."""
return self.field_name
필드
https://brunch.co.kr/@ddangdol/1
모델에서 가장 중요하고, 유일하게 필수적인 부분은 데이터베이스 필드 목록을 정의하는 것입니다. 필드는 클래스 속성으로 정의됩니다. clean, save, delete 같은 :doc:모델 API
와 충돌할 수 있는 단어를 필드 이름으로 사용하지 않도록 주의하세요.
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
Field Option
https://brunch.co.kr/@ddangdol/3
- null
- blank
- choice
- db_column
- db_index
- db_tablespace
- default
- editable
- error_messages
- help_text
- primary_key
- unique
- verbose_name
- validators
Field Type
https://docs.djangoproject.com/ko/3.2/ref/models/fields/#field-types
https://brunch.co.kr/@ddangdol/4
- AutoField(**options)
- BigAutoField(**options)
- BigIntegerField(**options)
- BinaryField(max_length=None, **options)
- BooleanField(**options)
- CharField(max_length=None, **options)
- For large amounts of text, use TextField.
- DateField(auto_now=False, auto_now_add=False, **options)
- DateTimeField(auto_now=False, auto_now_add=False, **options)
- DecimalField(max_digits=None, decimal_places=None, **options)
- DurationField(**options)
- EmailField(max_length=254, **options)
- FileField(upload_to=None, max_length=100, **options)
- FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100, **options)
- FloatField(**options)
- ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)
- IntegerField(**options)
- GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)
- JSONField(encoder=None, decoder=None, **options)
- NullBooleanField(**options)
- PositiveBigIntegerField(**options)
- PositiveIntegerField(**options)
- PositiveSmallIntegerField(**options)
- SlugField(max_length=50, **options)
- SmallAutoField(**options)
- SmallIntegerField(**options)
- TextField(**options)
- TimeField(auto_now=False, auto_now_add=False, **options)
- URLField(max_length=200, **options)
- UUIDField(**options)
Relationship fields
https://docs.djangoproject.com/ko/3.2/ref/models/fields/#module-django.db.models.fields.related
https://brunch.co.kr/@ddangdol/5
- ForeignKey(to, on_delete, **options)
- ManyToManyField(to, **options)
- OneToOneField(to, on_delete, parent_link=False, **options)
meta 데이터
https://docs.djangoproject.com/en/2.0/ref/models/options/#model-meta-options
아래와 같이 class Meta를 선언하여 모델에 대한 모델-레벨의 메타데이타를 선언
class Meta:
ordering = ['-my_field_name']
모델 타입을 쿼리(query)할 때 반환되는 기본 레코드 순서를 제어
예를 들어, 우리가 기본적으로 아래와 같이 책들을 정렬하려고 한다면:
ordering = ['title', '-pubdate']
책들은 A-Z까지 알파벳 순으로 정렬되고, 그 후에는 제목(title) 안에 있는 발행일 별로 가장 최근 것부터 가장 오래된 것 순으로 정렬
model methods
비지니스 로직을 담는 곳
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
def baby_boomer_status(self):
"Returns the person's baby-boomer status."
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
@property
def full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
Model inheritance
https://docs.djangoproject.com/en/3.2/topics/db/models/#model-inheritance
from django.db import models
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract = True
ordering = ['name']
class Unmanaged(models.Model):
class Meta:
abstract = True
managed = False
class Student(CommonInfo, Unmanaged):
home_group = models.CharField(max_length=5)
class Meta(CommonInfo.Meta, Unmanaged.Meta):
pass
'Study > Django' 카테고리의 다른 글
[Django] settings.py - cors, static path (0) | 2021.05.11 |
---|---|
[Django] Serializers (0) | 2021.05.11 |
[Django] app, mysql 추가 및 연결 (0) | 2021.05.10 |
[Django + pycharm] 개발환경 세팅 (0) | 2021.05.02 |
Python 가상환경 설치 및 비교 (0) | 2021.05.02 |