Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Basic Django ORM

1,072 views

Published on

Published in: Technology
  • Be the first to like this

Basic Django ORM

  1. 1. Basic Django ORMParkayun-Rainist Co.Ltd
  2. 2. What’s ORM? Object Relational Mapping 일종의 DB Framework. ORM은 객체를 DB에 저장해 준다. ORM은 DB에 저장된 Data로부터 객체를 생성해준다.
  3. 3. Why use ORM? 깔끔한 코드를 유지할 수 있다. 생산성이 무지막지하게 증가한다. 테스트를 쉽게 해준다.
  4. 4. What’s Django ORM? Django MVC패턴중 Model에 해당. django.db.models.Model을 상속. order_by, filter, exists, exclude등 많은 함수들. 다양한 Database 지원 postgres, sqlite, mysql, mssql, oracle 유연한 맵핑가능. many to one, one to one, many to many Django Forms 모듈과 연동 가능. Model form 트랜젝션 컨트롤 가능. non_atmoic_requests, commit_on_success 등
  5. 5. Basic SQL vs ORM 0id username password1 admin 912ec803b2ce49e4am5106…위와 같은 테이블을 만들때SQL- CREATE TABLE `user` (‘id’ int NOT NULL AUTO_INCREMENT,‘username’ VARCHAR(10) NOT NULL, ‘password’ VARCHAR(30)NOT NULL, PRIMARY KEY(id));Django ORM- class User(models.Model):- username = models.CharField(max_length=10)- password = models.CharField(max_length=30)
  6. 6. Basic SQL vs ORM 1id username password1 admin 912ec803b2ce49e4am5106…username을 검색할 때SQL- SELECT username FROM `user_table` WHERE `id` = 1;Django ORM- User.objects.get(id=1).username
  7. 7. Basic SQL vs ORM 2test 유저 생설할 때SQL with PHP- $sql= SELECT * FROM `user_table` WHERE `username` = ‘test’;- $query = mysql_query($sql);- $flag = True;- if (mysql_fetch_array($query)) {- 유저가 있나 없나 어쩌고 저쩌고- }- if ($flag) mysql_query(“INSERT INTO `user_table` VALUES (‘test’,md5(‘test’));Django ORM- User.objects.get_or_create(username=‘test’, password=md5(‘test’))
  8. 8. One to One Relationshipsid placeRestaurant 테이블의 place컬럼과 Place테이블을맵핑class Place(models.Model):name = models.CharField(max_length=15)address = models.CharField(max_length=80)class Restaurant(models.Model):place = models.OneToOneField(Place)p1 = Place.obejcts.create(name=‘test’, address=‘test address’)Restaurant.objects.create(place=p1)id name address
  9. 9. Many to Many Relationshipsid content tagArticle 테이블의 tag컬럼과 Tag필드를 맵핑class Tag(models.Model):title = models.CharField(max_length=15)class Meta:ordering = (‘title’,)class Article(models.Model):content = models.CharField(max_length=100)tag = models.ManyToManyField(Tag)a1 = Article.object.create(‘test article’)a1.save()a1.tag.add(Tag.objects.create(‘test tag1’), Tag.objects.create (‘test tag2’))id name

×