[Django] C.R.U.D

Minjeong Bak·2021년 10월 20일
1

PYTHON/Django

목록 보기
12/14
post-thumbnail

Main Model

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    job = models.CharField(max_length=50)
Person table
id name age job

Create

Person table
id name age job
1 A 33 CEO
2 B 20 Developer
3 C 28 Developer
  • python manage.py shell
>>>from.person.models import Person
>>>Person.objects.create(name='A', age=33, job='CEO')
>>>Person.objects.create(name='B', age=20, job='Developer')
>>>Person.objects.create(name='C', age=28, job='Developer')
  • objects : Person model class를 통해서 Database에 Data를 생성/조회/수정/삭제 작업을 제공하는 Manager class
  • create : manager class의 method로서, 해당 method가 호출되면 Database에 쿼리 작업 수행

Read

Person table
id name age job
1 A 33 CEO
2 B 20 Developer
3 C 28 Developer
4 D 33 Developer
  • python manage.py shell
>>>from.person.models import Person
>>>Person.objects.get(id=1)
>>><person: Person object (1)>
>>>Person.objects.filter(age=33)
>>><QuerySet[<Person: Person object (1)>, <Person: Person object (4)>]>
>>>person = Person.objects.filter(age=33)
>>>person
>>><QuerySet[<Person: Person object (1)>, <Person: Person object (4)>]>
>>>person[0].name
>>>A
  • QuerySet : djnago에서 객체들을 편하게 관리하기 위해서 새롭게 만들어놓은 자료형. List 형식

Update

Person table
id name age job
1 A 33 CEO
2 B 20 Developer
3 C 28 Developer
4 D 33 Developer

 ⬇︎

Person table
id name age job
1 A 33 Firefighter
2 B 20 Developer
3 C 28 Developer
4 D 33 Firefighter
  • python manage.py shell
>>>from.person.models import Person
>>>In : Person.objects.filter(age=33)
>>>Out : <QuerySet[<Person: Person object (1)>, <Person: Person object (4)>]>
>>>In : Person.objects.filter(age=33).update(job='Firefighter')
>>>Out : 2

Delete

Person table
id name age job
1 A 33 Firefighter
2 B 20 Developer
3 C 28 Developer
4 D 33 Firefighter

⬇︎

Person table
id name age job
1
2 B 20 Developer
3 C 28 Developer
4
  • python manage.py shell
>>>from.person.models import Person
>>>In : Person.objects.filter(age=33)
>>>Out : <QuerySet[<Person: Person object (1)>, <Person: Person object (4)>]>
>>>In : Person.objects.filter(age=33).delete()
>>>Out : (2, {'products.Product'})

0개의 댓글