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

Reference

  1. official guide

Update

Delete