Model CRUD - pai-plznw4me/django-initializer GitHub Wiki
Model CRUD
- Django Model Create / Read / Update / Delete ์ ๋ํด ๋ฐฐ์ ๋ด ๋๋ค.
Model ๊ตฌ์กฐ
class Question(models.Model):
question_text = models.CharField(max_length=200, primary_key=True)
pub_date = models.DateTimeField(verbose_name='date published')
def __str__(self):
return self.question_text
@admin.display(
boolean=True,
ordering='pub_date',
description='Published recently?',
)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
(โ ๏ธWarningโ ๏ธ ์๋ ํํ ๋ฆฌ์ผ์ ์งํํ๊ธฐ์ Migrate ๊ฐ ์ด๋ฏธ ์ํ๋์ด์ผ ํฉ๋๋ค.) (โ ๏ธWarningโ ๏ธ primary_key ์ ์ง์ ํ์ง ์์ผ๋ฉด ์๋์ผ๋ก pk ๋ field ์ ๋ง๋ค์ด primary key ๋ก ์ง์ ํฉ๋๋ค. 1๋ถํฐ ์์ฐจ์ ์ผ๋ก ๋ง๋ค์ด์ง ์์๋๋ก ์๋์ผ๋ก pk์ ๋ถ์ฌํฉ๋๋ค. )
Create
# Model constructor ์ ํ์ฉํ instance ์์ฑํ๊ธฐ
Question(question_text=question, pub_date=timezone.now()).save()
# objects.create ์ ํ์ฉํ ์์ฑํ๊ธฐ
Question.objects.create(question_text=question, pub_date=timezone.now())
Read
๋ชจ๋ ๊ฐ์ฒด(QuerySet) ๊ฐ์ ธ์ค๊ธฐ
Question.objects.all()
for q in Question.objects.all():
print(q.id, q.question_text, q.pub_date)
Table ๋ด field ์ด๋ฆ ๊ฐ์ ธ์ค๊ธฐ
fields = Question._meta.get_fields()
ํน์ column ๊ฐ์ ธ์ค๊ธฐ
Question.objects.values("๊ฐ์ ธ์ฌ column name")
ํน์ row ๊ฐ์ ธ์ค๊ธฐ
Question db ์ column ๋ด์ฉ์ด pk, id, pub_date, question_text ๋ผ๊ณ ํ ๋ ํ๋์ instance ๋ง ๊ฐ์ ธ์ด
get ์ ํ๋์ ๊ฐ์ฒด๋ง ๊ฐ์ ธ์ค๊ณ ๋ง์ฝ ๊ฐ์ ธ์์ผ ํ ๊ฐ์ฒด๊ฐ 2๊ฐ ์ด์์ด๋ฉด ์๋ฌ๋ฅผ ์ถ๋ ฅํ๋ค.
filter ๋ ์ฌ๋ฌ๊ฐ์ ๊ฐ์ฒด๋ฅผ ๊ฐ์ ธ์ฌ์ ์๋ค. filter ๋ chaining ์ด ๊ฐ๋ฅํ๋ค.
Question.objects.get(pk=1)
Question.objects.filter(pk=1)
Question.objects.get(**{"pk":1})
Question.objects.get(id=1)
Question.objects.filter(id=1)
Question.objects.get(**{"id":1})
Question.objects.get(pub_date=timezone.now())
Question.objects.filter(pub_date=timezone.now())
Question.objects.get(**{pub_date:timezone.now()})
Question.objects.get(question_text='hello')
Question.objects.filter(question_text='hello')
Question.objects.get(**{question_text:hello})