Aivle Til 230512 Django 3
title: AIVLE TIL (‘23.05.12) Django (3) date: 2023-05-12 15:18:20.444 +0000 categories: [에이블스쿨] tags: [‘aivle’] description: 포스팅이 많이 밀렸다. 알고리즘도 써야하고.. CS 스터디 한 것도 써야하고.. image: /assets/posts/2023-05-12-aivle-til-230512-django-3/thumbnail.png math: true —
ORM (Object Relation Mapping)
ORM (Object Relation Mapping)은 객체-관계-맵핑의 약자로, 말 그대로 객체와 관계를 맵핑해주는 도구이다.
코드(객체)를 통해 관계형 데이터베이스를 다룰 수 있게한다.
ORM의 장점
- 유지보수의 편의성 증가
- SQL과 코드를 섞어 사용하지 않으므로 가독성 증가
- 객체지향적 접근이 가능하므로 재사용 및 유지보수가 용이
- SQL 쿼리 중복 방지
- DBMS에 대한 의존도가 낮아짐
- DBMS에 따라 문법, 기능이 달라지는 것을 신경쓸 필요 없고 ORM을 통해 일관된 방법으로 다룰 수 있음
- 보안 강화
- ORM에서 SQL 삽입 공격을 차단
Django ORM 사용
django에서 사용할 수 있는 라이브러리인 django-extensions
를 통해 관계형 데이터베이스를 객체로 다룰 수 있다.
django shell 사용하기
pip install django-extensions
로 라이브러리 설치- 사용할 프로젝트의 settings.py > INSTALLED_APPS에 django-extensions 추가
- 이제
python manage.py shell_plus
로 django shell 진입 가능
조회
1
2
3
4
5
6
7
8
# 모든 사용자 가져오기
User.objects. all()
>> SELECT * FROM user_auth;
# 이메일 주소로 사용자 필터링하기
User.objects. filter(username='admin' )
>> SELECT * FROM user_auth WHERE username='admin';
# 사용자 이름으로 정렬하기
>> SELECT * FROM user_auth ORDER BY username ASC;
- QuerySet 객체를 받아오며, 이를 변수로 저장하면 반복문 등에서 하나씩 꺼내어 사용할 수 있다.
QuerySet.__dict__
: 객체를 딕셔너리로 변환
1
2
3
4
5
6
7
8
9
10
11
12
{'_state': <django.db.models.base.ModelState at 0x26df4d530a0>,
'id': 1,
'password': 'pbkdf2_sha256$$ 600000 $$ pLjDzijWJbFyVp6Vfi8cdq$26xMiL5jalyIUwYFNNL2J99LGgOCsWWjHvgZ7dZt2eE=',
'last_login': datetime.datetime(2023, 5, 12, 1, 48, 54, 123218, tzinfo=datetime.timezone.utc),
'is_superuser': True,
'username': 'admin',
'first_name': '',
'last_name': '',
'email': '',
'is_staff': True,
'is_active': True,
'date_joined': datetime.datetime(2023, 5, 12, 0, 53, 40, 498738, tzinfo=datetime.timezone.utc)}
생성
1
2
3
4
5
6
7
8
9
10
11
12
# 새로운 사용자 생성하기
new_user = User.objects.create(
username= 'exampleuser' ,
password= 'examplepassword' ,
email= 'example@example.com' )
# 새로운 사용자 생성하기2
new_user = User(
username= 'exampleuser' ,
password= 'examplepassword' ,
email= 'example@example.com')
new_user.save()
생성에는 두 가지 방법이 있다.
create()
메서드 이용- 데이터 객체를 직접 만든 뒤,
save()
메서드를 통해 저장
수정
1
2
3
4
5
6
7
# 사용자 정보 업데이트하기
user = User.objects.get(username= 'exampleuser' )
user.email = 'newemail@example.com'
user.save()
# 사용자 삭제하기
user = User.objects.get(username= 'exampleuser' )
user.delete()
- 기본적으로 조회문을 통해 데이터를 객체에 담아 수정한다.
save()
,delete()
등을 통해 데이터 조작을 확정한다.create()
역시 데이터 조작을 확정하는 것이기 때문에save()
를 하지 않아도 테이블에 데이터가 추가된다.
로깅
- settings.py 에서 로그 설정을 하면 SQL 사용 내역과 어떤 과정을 거쳐 DB의 자료를 조회하는지 로그를 남길 수 있다.
- DB의 성능 저하, 오류 등이 발생할 때 추적하는 것에 용이하다.
객체지향과 Python
데이터 구조체의 역사 (데이터 처리 방식의 진화)
초창기 - Structure Type의 형태
클래스에 아무런 메서드 없이 데이터만 담아서 사용하는 것
1
2
3
4
5
6
7
8
9
10
11
class User:
def __init__(self, id, name, email):
self. id = id
self.name = name
self.email = email
users = [
User(id=1, name='blackdew' , email= 'blackdew7@gmail.com' ),
User(id=2, name='django' , email= 'django@naver.com' ),
User(id=3, name='python' , email= 'python@gmail.com' ),
]
User 클래스로 생성된 인스턴스는 id, name, email 값을 가지는 형식의 일종의 데이터 자료형처럼 사용할 수 있다. 데이터 구조를 명시함으로써 코드를 읽기만해도 데이터 구조를 쉽게 파악할 수 있다는 장점을 갖는다.
단점
- struct 타입의 데이터 구조를 정확히 알고 있어야만 데이터를 다룰 수 있다.
- 마찬가지로 데이터 구조를 알지 못하면 이 데이터를 다루는 코드를 알기 어렵다
발전된 형태 - Class 문법
데이터를 다루는 함수를 클래스 안에 담아서 사용하는 것
1
2
3
4
5
6
7
8
9
10
11
12
13
class User:
def __init__(self, id, name, email):
self. id = id
self.name = name
self.email = email
def domain(self):
return self.email.split('@')[-1]
def filter_domain(users, domain):
return [u for u in users if u.domain() == domain]
filtered = filter_domain(users, 'gmail.com' )
for f in filtered:
print(f.name, f.email)
사용자는 데이터의 구조를 몰라도 domain() 메소드의 기능만 알고 있으면 사용할 수 있다.
현재 - 객체 지향
캡슐화, 다형성, 상속을 이용하여 객체들을 연결 시켜 프로그래밍 하는 것
코드 재사용, 유지 보수를 감소시키는 장점이 있다.
Python Class
- 파이썬에서 ‘객체 지향’을 위해 이해해야 하는 것들
- 속성(property)과 행동(method)의 관점 이해 및 사용
- 상속에 대한 이해
- self에 대한 이해
- magic methods에 대한 이해
파이썬의 기본 클래스
- list, dict, set 과 같은 자료구조는 모두 하나의 객체들이다.
dir()
내장 함수는 객체가 어떤 메소드를 갖고 있는지 출력한다.
기본 클래스 상속하여 강화하기
- map 함수를 메서드 형식으로 사용하고 싶다면?
1
2
3
4
5
class xlist(list):
def map(self, f):
s = map(f, self)
return xlist(s)
→ 이제 리스트를 선언해서 arr.map(function)을 이용하면 리스트를 반환받을 수 있다!
객체지향 방법론과 데이터 베이스
- Class 기반 객체지향 방법론을 웹에 데이터베이스 처리에 사용하는 것은 매우 어렵다.
- 객체 지향 프로그래밍과 관계형 데이터베이스는 서로 다른 패러다임을 갖고 있다.
- 쿼리에 따라 가져오는 데이터의 형태가 다르기 때문에 클래스 문법을 통해 일관적으로 처리할 수 없다.
- 데이터베이스의 스키마가 바뀌면 Class의 코드도 바꾸어주어야 하기 때문에 유지보수가 복잡해진다.
- 이를 극복하는 방법론이 바로 ORM이다.
- 데이터페이스의 테이블을 객체 지향 언어의 클래스로 맵핑함
- 이를 통해 코드 내에서 객체를 처리하는 것 처럼 데이터를 처리할 수 있다.
- django에서는 모델을 통해 ORM을 다룰 수 있다.
Django Model
DB와 ORM을 통해 데이터를 주고받을 수 있도록 데이터 구조를 지정한다. Model을 거쳐 객체화된 데이터는 view에서 파이썬 코드를 통해 다양한 처리가 가능하다.
모델 선언 과정
1. 클래스 생성
1
2
3
4
5
6
7
8
# models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length = 100)
content = models.TextField()
created_at = models.DateField(auto_now_add = True)
published_at = models.DateField(null = True)
django 문법에 의해 모델은
models.Model
을 상속 받아야 한다.- 저장할 자료의 Field(자료형)를 선언해야한다.
- 공식문서 : https://docs.djangoproject.com/en/4.2/ref/models/fields/#model-field-types
- 커스텀 자료형을 만들어 사용할수도 있다.
2. Migrate
이 과정을 거치친 후 migration을 만들어야 한다.
python manage.py makemigrations <app 이름>
: 지정한 앱에 migration을 추가한다.
migrate 전
migrations 파일 생성 후
- migrate 정보를 저장하는 일종의 버전 역할을 하는 파이썬 파일이 생성되었다.
- 이제 migrate를 할 경우 manage.py가 새로운 버전 파일을 읽어 테이블 구조를 생성한다.
migrate 후
- class에 선언한 구조대로 테이블이 생성되었다.
3. 관리자페이지 등록
- 테이블을 생성한 application의
admin.py
에 추가한 모델을 등록하면 된다.
1
2
3
4
5
6
# admin.py
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Post)
- 생성한 테이블이 관리자페이지에 등록되었다.
버전 되돌리기
- 만약 이전 버전으로 돌아가고 싶다면
migrate
명령어를 통해 쉽게 돌아갈 수 있다. python manage.py migrate blog 0001
: blog앱에서 선언했던 0001버전으로 돌아간다.
Model Field의 종류
- CharField : 짧은 문자열, max_length로 최대 길이를 지정해야한다.
- TextField : 긴 문자열, 최대 길이를 지정할 필요가 없다.
- IntergerField : 정수 값 필드
- DataField : 날짜 값 필드
- 관계형 필드 : SQL에서 JOIN과 동일한 역할을 한다.
- ForeignKey : 일대다 관계를 형성하는 관계형 필드
- OneToOneField : 일대일 관계를 형성하는 관계형 필드
- ManyToManyField : 다대다 관계를 형성하는 관계형 필드
- 연결하려는 모델을 매개변수로 입력
1 2 3 4
class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) year = models.IntegerField()
- User와 Student는 일대일 관계이다 → 한명의 유저는 한명의 학생이다.
- User는 장고에서 제공하는 기본 모델이기 때문에 건드리지 않고 이런식으로 일대일 관계를 연결하여 사용하는 경우가 많다.
- 관계데이터베이스의 관계성은 기능도 많고 복잡함도 많으니 되도록 따로 공부하도록 하자..
관계형 필드
- 자식 객체 → 부모 객체 접근 (일대일, 다대다에서 다)
- 연결된 테이블의 데이터를 테이블명 체이닝을 통해 가져올 수 있다.
- ex) user와 student 테이블이 연결되었을 때 →
user.student.name
식으로 사용 가능
- 부모 객체 → 자식 객체 접근 (다대다, 다대일에서 일)
- 하나의 데이터만 가져오는 것이 불가능하므로 필드명에 더해 조건을 넣어주어야 한다.
- ex)
student.course_set.all()
→ 모두 가져오기 - ex)
student.course_set.get(id=5)
→ 연결된 데이터중 id 컬럼값이 5인 데이터만 가져오기 - 위와 같이
<테이블명>_set
으로 묶어 사용한다. → 필드가 지정되어있을 경우 필드로 사용하면 된다.
ORM을 View에서 사용하기
shell_plus에서 사용했던 ORM 문법을 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
# views.py
def post_list(req, id):
posts = models.Post.objects.all()
post = posts.get(id=id)
return render(req,
'blog/post.html',
{
'title' : post.title,
'content': post.content
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
<!-- post.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2></h2>
<p><!doctype html>
<!-- `site.alt_lang` can specify a language different from the UI -->
<html lang="ko" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#f7f7f7">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1b1b1e">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta
name="viewport"
content="width=device-width, user-scalable=no initial-scale=1, shrink-to-fit=no, viewport-fit=cover"
><!-- Setup Open Graph image -->
<!-- Begin Jekyll SEO tag v2.8.0 -->
<meta name="generator" content="Jekyll v4.3.4" />
<meta property="og:title" content="Aivle Til 230510 Django 1" />
<meta property="og:locale" content="ko" />
<meta name="description" content="AI 관련하여 배운 것, 개발한 것, 경험한 것을 정리합니다." />
<meta property="og:description" content="AI 관련하여 배운 것, 개발한 것, 경험한 것을 정리합니다." />
<link rel="canonical" href="https://cjkangme.github.io/posts/aivle-til-230510-django-1/" />
<meta property="og:url" content="https://cjkangme.github.io/posts/aivle-til-230510-django-1/" />
<meta property="og:site_name" content="cjkangme Devlog" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2023-05-10T00:00:00+09:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:title" content="Aivle Til 230510 Django 1" />
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"BlogPosting","dateModified":"2024-12-12T19:01:37+09:00","datePublished":"2023-05-10T00:00:00+09:00","description":"AI 관련하여 배운 것, 개발한 것, 경험한 것을 정리합니다.","headline":"Aivle Til 230510 Django 1","mainEntityOfPage":{"@type":"WebPage","@id":"https://cjkangme.github.io/posts/aivle-til-230510-django-1/"},"url":"https://cjkangme.github.io/posts/aivle-til-230510-django-1/"}</script>
<!-- End Jekyll SEO tag -->
<title>Aivle Til 230510 Django 1 | cjkangme Devlog
</title>
<!--
The Favicons for Web, Android, Microsoft, and iOS (iPhone and iPad) Apps
Generated by: https://realfavicongenerator.net/
-->
<link rel="apple-touch-icon" sizes="180x180" href="/assets/img/favicons/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/assets/img/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/assets/img/favicons/favicon-16x16.png">
<link rel="manifest" href="/assets/img/favicons/site.webmanifest">
<link rel="shortcut icon" href="/assets/img/favicons/favicon.ico">
<meta name="apple-mobile-web-app-title" content="cjkangme Devlog">
<meta name="application-name" content="cjkangme Devlog">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-config" content="/assets/img/favicons/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<!-- Resource Hints -->
<link rel="preconnect" href="https://fonts.googleapis.com" >
<link rel="dns-prefetch" href="https://fonts.googleapis.com" >
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="dns-prefetch" href="https://fonts.gstatic.com" >
<link rel="preconnect" href="https://cdn.jsdelivr.net" >
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net" >
<!-- Bootstrap -->
<!-- Theme style -->
<link rel="stylesheet" href="/assets/css/jekyll-theme-chirpy.css">
<!-- Web Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400&family=Source+Sans+Pro:wght@400;600;700;900&display=swap">
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.1/css/all.min.css">
<!-- 3rd-party Dependencies -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tocbot@4.32.2/dist/tocbot.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/loading-attribute-polyfill@2.1.1/dist/loading-attribute-polyfill.min.css">
<!-- Image Popup -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox@3.3.0/dist/css/glightbox.min.css">
<!-- Scripts -->
<script src="/assets/js/dist/theme.min.js"></script>
<!-- JS selector for site. -->
<!-- commons -->
<!-- layout specified -->
<!-- image lazy-loading & popup & clipboard -->
<script defer src="https://cdn.jsdelivr.net/combine/npm/simple-jekyll-search@1.10.0/dest/simple-jekyll-search.min.js,npm/loading-attribute-polyfill@2.1.1/dist/loading-attribute-polyfill.umd.min.js,npm/glightbox@3.3.0/dist/js/glightbox.min.js,npm/clipboard@2.0.11/dist/clipboard.min.js,npm/dayjs@1.11.13/dayjs.min.js,npm/dayjs@1.11.13/locale/en.js,npm/dayjs@1.11.13/plugin/relativeTime.js,npm/dayjs@1.11.13/plugin/localizedFormat.js,npm/tocbot@4.32.2/dist/tocbot.min.js"></script>
<script defer src="/assets/js/dist/post.min.js"></script>
<!-- Pageviews -->
<!-- Display GoatCounter pageviews -->
<script>
document.addEventListener('DOMContentLoaded', () => {
const pv = document.getElementById('pageviews');
if (pv !== null) {
const uri = location.pathname.replace(/\/$/, '');
const url = `https://cjkangme.goatcounter.com/counter/${encodeURIComponent(uri)}.json`;
fetch(url)
.then((response) => response.json())
.then((data) => {
const count = data.count.replace(/\s/g, '');
pv.innerText = new Intl.NumberFormat().format(count);
})
.catch((error) => {
pv.innerText = '1';
});
}
});
</script>
<!-- PWA -->
<script
defer
src="/app.min.js?baseurl=®ister=true"
></script>
<!-- Web Analytics -->
<!-- GoatCounter -->
<script
async
src="https://gc.zgo.at/count.js"
data-goatcounter="https://cjkangme.goatcounter.com/count"
></script>
<!-- A placeholder to allow defining custom metadata -->
</head>
<body>
<!-- The Side Bar -->
<aside aria-label="Sidebar" id="sidebar" class="d-flex flex-column align-items-end">
<header class="profile-wrapper">
<a href="/" id="avatar" class="rounded-circle"><img src="/assets/img/profile/profile.jpg" width="112" height="112" alt="avatar" onerror="this.style.display='none'"></a>
<a class="site-title d-block" href="/">cjkangme Devlog</a>
<p class="site-subtitle fst-italic mb-0">cjkangme(누렁이)의 기술 블로그</p>
</header>
<!-- .profile-wrapper -->
<nav class="flex-column flex-grow-1 w-100 ps-0">
<ul class="nav">
<!-- home -->
<li class="nav-item">
<a href="/" class="nav-link">
<i class="fa-fw fas fa-home"></i>
<span>HOME</span>
</a>
</li>
<!-- the real tabs -->
<li class="nav-item">
<a href="/categories/" class="nav-link">
<i class="fa-fw fas fa-stream"></i>
<span>CATEGORIES</span>
</a>
</li>
<!-- .nav-item -->
<li class="nav-item">
<a href="/tags/" class="nav-link">
<i class="fa-fw fas fa-tags"></i>
<span>TAGS</span>
</a>
</li>
<!-- .nav-item -->
<li class="nav-item">
<a href="/archives/" class="nav-link">
<i class="fa-fw fas fa-archive"></i>
<span>ARCHIVES</span>
</a>
</li>
<!-- .nav-item -->
<li class="nav-item">
<a href="/about/" class="nav-link">
<i class="fa-fw fas fa-info-circle"></i>
<span>ABOUT</span>
</a>
</li>
<!-- .nav-item -->
</ul>
</nav>
<div class="sidebar-bottom d-flex flex-wrap align-items-center w-100">
<button type="button" class="btn btn-link nav-link" aria-label="Switch Mode" id="mode-toggle">
<i class="fas fa-adjust"></i>
</button>
<span class="icon-border"></span>
<a
href="https://github.com/cjkangme"
aria-label="github"
target="_blank"
rel="noopener noreferrer"
>
<i class="fab fa-github"></i>
</a>
<a
href="https://twitter.com/"
aria-label="twitter"
target="_blank"
rel="noopener noreferrer"
>
<i class="fa-brands fa-x-twitter"></i>
</a>
<a
href="javascript:location.href = 'mailto:' + ['nureongi0214','gmail.com'].join('@')"
aria-label="email"
>
<i class="fas fa-envelope"></i>
</a>
<a
href="/feed.xml"
aria-label="rss"
>
<i class="fas fa-rss"></i>
</a>
</div>
<!-- .sidebar-bottom -->
</aside>
<!-- #sidebar -->
<div id="main-wrapper" class="d-flex justify-content-center">
<div class="container d-flex flex-column px-xxl-5">
<!-- The Top Bar -->
<header id="topbar-wrapper" aria-label="Top Bar">
<div
id="topbar"
class="d-flex align-items-center justify-content-between px-lg-3 h-100"
>
<nav id="breadcrumb" aria-label="Breadcrumb">
<span>
<a href="/">Home</a>
</span>
<span>Aivle Til 230510 Django 1</span>
</nav>
<!-- endof #breadcrumb -->
<button type="button" id="sidebar-trigger" class="btn btn-link">
<i class="fas fa-bars fa-fw"></i>
</button>
<div id="topbar-title">
Post
</div>
<button type="button" id="search-trigger" class="btn btn-link">
<i class="fas fa-search fa-fw"></i>
</button>
<search id="search" class="align-items-center ms-3 ms-lg-0">
<i class="fas fa-search fa-fw"></i>
<input
class="form-control"
id="search-input"
type="search"
aria-label="search"
autocomplete="off"
placeholder="Search..."
>
</search>
<button type="button" class="btn btn-link text-decoration-none" id="search-cancel">Cancel</button>
</div>
</header>
<div class="row flex-grow-1">
<main aria-label="Main Content" class="col-12 col-lg-11 col-xl-9 px-md-4">
<!-- Refactor the HTML structure -->
<!--
In order to allow a wide table to scroll horizontally,
we suround the markdown table with `<div class="table-wrapper">` and `</div>`
-->
<!--
Fixed kramdown code highlight rendering:
https://github.com/penibelst/jekyll-compress-html/issues/101
https://github.com/penibelst/jekyll-compress-html/issues/71#issuecomment-188144901
-->
<!-- Change the icon of checkbox -->
<!-- Handle images -->
<!-- take out classes -->
<!-- lazy-load images -->
<!-- make sure the `<img>` is wrapped by `<a>` -->
<!-- create the image wrapper -->
<!-- combine -->
<!-- take out classes -->
<!-- lazy-load images -->
<!-- make sure the `<img>` is wrapped by `<a>` -->
<!-- create the image wrapper -->
<!-- combine -->
<!-- take out classes -->
<!-- lazy-load images -->
<!-- make sure the `<img>` is wrapped by `<a>` -->
<!-- create the image wrapper -->
<!-- combine -->
<!-- Add header for code snippets -->
<!-- Create heading anchors -->
<!-- return -->
<article class="px-1" data-toc="true">
<header>
<h1 data-toc-skip>Aivle Til 230510 Django 1</h1>
<div class="post-meta text-muted">
<!-- published date -->
<span>
Posted
<!--
Date format snippet
See: ${JS_ROOT}/utils/locale-dateime.js
-->
<time
data-ts="1683644400"
data-df="ll"
data-bs-toggle="tooltip" data-bs-placement="bottom"
>
May 10, 2023
</time>
</span>
<!-- lastmod date -->
<span>
Updated
<!--
Date format snippet
See: ${JS_ROOT}/utils/locale-dateime.js
-->
<time
data-ts="1733997697"
data-df="ll"
data-bs-toggle="tooltip" data-bs-placement="bottom"
>
Dec 12, 2024
</time>
</span>
<div class="d-flex justify-content-between">
<!-- author(s) -->
<span>
By
<em>
<a href="https://github.com/cjkangme">Changjin Kang</a>
</em>
</span>
<div>
<!-- pageviews -->
<span>
<em id="pageviews">
<i class="fas fa-spinner fa-spin small"></i>
</em>
views
</span>
<!-- read time -->
<!-- Calculate the post's reading time, and display the word count in tooltip -->
<!-- words per minute -->
<!-- return element -->
<span
class="readtime"
data-bs-toggle="tooltip"
data-bs-placement="bottom"
title="2146 words"
>
<em>11 min</em> read</span>
</div>
</div>
</div>
</header>
<div id="toc-bar" class="d-flex align-items-center justify-content-between invisible">
<span class="label text-truncate">Aivle Til 230510 Django 1</span>
<button type="button" class="toc-trigger btn me-1">
<i class="fa-solid fa-list-ul fa-fw"></i>
</button>
</div>
<button id="toc-solo-trigger" type="button" class="toc-trigger btn btn-outline-secondary btn-sm">
<span class="label ps-2 pe-1">Contents</span>
<i class="fa-solid fa-angle-right fa-fw"></i>
</button>
<dialog id="toc-popup" class="p-0">
<div class="header d-flex flex-row align-items-center justify-content-between">
<div class="label text-truncate py-2 ms-4">Aivle Til 230510 Django 1</div>
<button id="toc-popup-close" type="button" class="btn mx-1 my-1 opacity-75">
<i class="fas fa-close"></i>
</button>
</div>
<div id="toc-popup-content" class="px-4 py-3 pb-4"></div>
</dialog>
<div class="content">
<hr />
<p>title: AIVLE TIL (‘23.05.10) Django (1)
date: 2023-05-10 14:44:19.075 +0000
categories: [에이블스쿨]
tags: [‘aivle’]
description: 문법은 어짜피 외우기이니 개념 위주로 공부하자
image: /assets/posts/2023-05-10-aivle-til-230510-django-1/thumbnail.png</p>
<hr />
<h1 id="django-개요">Django 개요</h1>
<p>django는 파이썬으로 만들어진 웹 프레임워크로 빠르고 효율적으로 백엔드 시스템을 구현할 수 있다.</p>
<h2 id="django-특징"><span class="me-2">Django 특징</span><a href="#django-특징" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h2>
<h3 id="장점"><span class="me-2">장점</span><a href="#장점" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li>매우 복잡하고 다양한 기능을 제공하기 때문에, 비교적 큰 백엔드 서비스도 단기간에 구현하는 것이 가능하다.</li>
<li>이미 만들어진 모듈을 상속받아 커스터마이징 할 수 있어 어느정도의 유연성을 갖고 있다.</li>
<li>관리자 인터페이스를 기본 제공한다.</li>
</ul>
<h3 id="단점"><span class="me-2">단점</span><a href="#단점" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li>기능이 많고 복잡한 만큼 익혀야하는 개념이 많고, 문법이 다소 복잡하고 까다로운 편이다.</li>
</ul>
<h1 id="가상-환경">가상 환경</h1>
<p>이번 과정에서는 django 프로젝트를 anaconda가 제공하는 가상 환경에서 관리할 것이다.</p>
<h2 id="가상-환경-1"><span class="me-2">가상 환경</span><a href="#가상-환경-1" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h2>
<h3 id="가상환경이-필요한-이유"><span class="me-2">가상환경이 필요한 이유</span><a href="#가상환경이-필요한-이유" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<p>각 프로젝트는 프로젝트마다 필요한 라이브러리와 그 버전이 다르다.
그런데 동일한 환경에서 각 프로젝트를 관리한다면 버전 호환 문제 및 라이브러리 간 충돌 문제가 발생할 수 있다.</p>
<p>이를 해결하기 위해 프로젝트 별로 격리된 환경을 생성한 것이 가상 환경이다.</p>
<h3 id="언어별-오픈소스-라이브러리-저장소"><span class="me-2">언어별 오픈소스 라이브러리 저장소</span><a href="#언어별-오픈소스-라이브러리-저장소" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<p>가상환경에 필요한 패키지(라이브러리)를 쉽게 환경에 설치하는 기능을 제공한다.
가상환경의 생성, 복제 등 관리 기능을 제공해주기도 한다.</p>
<ul>
<li>python : pip, conda
<ul>
<li>pip은 가상환경 관리 기능이 없고</li>
<li>conda는 가상환경 관리 기능이 있다.</li>
</ul>
</li>
<li>nodejs : npm</li>
<li>php : composer</li>
<li>ruby : gems</li>
</ul>
<h2 id="환경-설정"><span class="me-2">환경 설정</span><a href="#환경-설정" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h2>
<h3 id="아나콘다-설치-및-환경변수-등록"><span class="me-2">아나콘다 설치 및 환경변수 등록</span><a href="#아나콘다-설치-및-환경변수-등록" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li><code class="language-plaintext highlighter-rouge">conda</code> 명령어를 anaconda prompt 외 프롬프트에서 사용하기 위한 과정</li>
<li>설치 시 <code class="language-plaintext highlighter-rouge">Add Anaconda3 to my PATH environmental value</code>를 체크하고 설치해야한다.
<ul>
<li>만약 이렇게 안했다면 설치 경로를 환경 변수에 직접 등록해야함</li>
</ul>
</li>
</ul>
<h3 id="conda-가상환경-세팅"><span class="me-2">conda 가상환경 세팅</span><a href="#conda-가상환경-세팅" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li><code class="language-plaintext highlighter-rouge">conda search python</code> : conda를 통해 설치 가능한 파이썬 버전 확인</li>
<li><code class="language-plaintext highlighter-rouge">conda create -n <가상환경 이름> python=3.10.11</code> : 지정한 이름의 환경 생성
<ul>
<li>처음에 환경에 설치될 패키지를 함께 지정할 수 있다.</li>
<li><code class="language-plaintext highlighter-rouge">conda activate <가상환경 이름></code> 으로 가상환경에 접속할 수 있다.</li>
</ul>
</li>
</ul>
<h3 id="conda를-통한-패키지-설치"><span class="me-2">conda를 통한 패키지 설치</span><a href="#conda를-통한-패키지-설치" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li><code class="language-plaintext highlighter-rouge">conda install <패키지이름></code></li>
</ul>
<p>설치하기 위한 패키지 이름은 보통 import에서 사용하는 패키지 이름과 동일하다.
하지만 다른 경우도 있기 때문에 conda 홈페이지에서 직접 검색하여 정확한 이름을 찾아보는 것이 좋다.
<a href="/assets/posts/2023-05-10-aivle-til-230510-django-1/img0.png" class="popup img-link shimmer"><img src="/assets/posts/2023-05-10-aivle-til-230510-django-1/img0.png" alt="img" loading="lazy"></a></p>
<h3 id="django-설치"><span class="me-2">Django 설치</span><a href="#django-설치" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li><code class="language-plaintext highlighter-rouge">conda install django</code></li>
</ul>
<p>성공적으로 django가 설치되었는지 확인하고 싶다면 파이썬 쉘을 실행해서 아래의 스크립트를 실행하면 된다.</p>
<div class="language-python highlighter-rouge"><div class="code-header">
<span data-label-text="Python"><i class="fas fa-code fa-fw small"></i></span>
<button aria-label="copy" data-title-succeed="Copied!"><i class="far fa-clipboard"></i></button></div><div class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
</pre></td><td class="rouge-code"><pre><span class="kn">import</span> <span class="n">django</span>
<span class="n">django</span><span class="p">.</span><span class="nf">get_version</span><span class="p">()</span>
</pre></td></tr></tbody></table></code></div></div>
<p>만약 버전 정보가 정상 출력된다면 성공적으로 import 한 것이다.</p>
<h1 id="django-프로젝트">Django 프로젝트</h1>
<h2 id="프로젝트-생성-및-실행"><span class="me-2">프로젝트 생성 및 실행</span><a href="#프로젝트-생성-및-실행" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h2>
<ul>
<li><code class="language-plaintext highlighter-rouge">django-admin startproject <프로젝트 이름></code></li>
</ul>
<p>지정한 이름의 프로젝트 폴더가 생성된다.</p>
<p>이후 서버를 실행 및 관리하기 위해서는 해당 프로젝트 디렉토리에서 작업을 진행해야 한다.</p>
<ul>
<li>(프로젝트 루트 디렉토리에서) <code class="language-plaintext highlighter-rouge">python manage.py runserver</code></li>
</ul>
<p>프로젝트 폴더에 있는 파이썬 파일을 바탕으로 서버를 배포하는 명령어이다.</p>
<p>별도로 설정하지 않으면 8000번 포트를 사용한다.</p>
<div class="language-plaintext highlighter-rouge"><div class="code-header">
<span data-label-text="Plaintext"><i class="fas fa-code fa-fw small"></i></span>
<button aria-label="copy" data-title-succeed="Copied!"><i class="far fa-clipboard"></i></button></div><div class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="rouge-code"><pre>May 10, 2023 - 12:23:41
Django version 4.2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
</pre></td></tr></tbody></table></code></div></div>
<p><code class="language-plaintext highlighter-rouge">manage.py</code>는 django 프로젝트를 진행하고 관리하는데 필요한 유틸리티를 제공하는 프로그램이다.</p>
<h1 id="mvt-구조">MVT 구조</h1>
<p><a href="/assets/posts/2023-05-10-aivle-til-230510-django-1/img1.png" class="popup img-link shimmer"><img src="/assets/posts/2023-05-10-aivle-til-230510-django-1/img1.png" alt="img" loading="lazy"></a></p>
<p>MVT 구조는 Model-Viewer-Template 구조의 약자이며, Django 프로젝트의 구조이다.
Django 프로젝트 폴더의 구성은 MVT 구조를 기반으로 한다.</p>
<p><a href="/assets/posts/2023-05-10-aivle-til-230510-django-1/img2.png" class="popup img-link shimmer"><img src="/assets/posts/2023-05-10-aivle-til-230510-django-1/img2.png" alt="img" loading="lazy"></a></p>
<h2 id="라우팅-urlspy"><span class="me-2">라우팅 (urls.py)</span><a href="#라우팅-urlspy" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h2>
<p>라우팅 기능을 제공하는 django 함수에는 다음과 같은 것들이 있다.</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">urlpatterns</code>
<ul>
<li>url과 view의 연결 목록을 리스트 형태로 저장하는 변수</li>
<li>프레임워크 문법이기 때문에 변수명을 그대로 사용해야 한다.</li>
</ul>
</li>
<li><code class="language-plaintext highlighter-rouge">path</code>
<ul>
<li>url 문자열과 view를 연결해주는 함수</li>
</ul>
</li>
<li><code class="language-plaintext highlighter-rouge">re_path</code>
<ul>
<li>정규표현식(regex)를 이용하여 url 문자열과 view를 연결해주는 함수</li>
<li>user/awesome_nickname 과 같이 게시글번호, 유저아이디 별로 패턴화된 url을 사용해야할 때 사용한다.</li>
</ul>
</li>
</ul>
<div class="language-python highlighter-rouge"><div class="code-header">
<span data-label-text="Python"><i class="fas fa-code fa-fw small"></i></span>
<button aria-label="copy" data-title-succeed="Copied!"><i class="far fa-clipboard"></i></button></div><div class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
</pre></td><td class="rouge-code"><pre><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
<span class="nf">path</span><span class="p">(</span><span class="sh">"</span><span class="s">admin/</span><span class="sh">"</span><span class="p">,</span> <span class="n">admin</span><span class="p">.</span><span class="n">site</span><span class="p">.</span><span class="n">urls</span><span class="p">),</span>
<span class="nf">path</span><span class="p">(</span><span class="sh">""</span><span class="p">,</span> <span class="n">index</span><span class="p">),</span>
<span class="nf">path</span><span class="p">(</span><span class="sh">"</span><span class="s">videos/<video_id>/</span><span class="sh">"</span><span class="p">,</span> <span class="n">video</span><span class="p">),</span>
<span class="nf">path</span><span class="p">(</span><span class="sh">"</span><span class="s">user/</span><span class="sh">"</span><span class="p">,</span> <span class="nf">include</span><span class="p">(</span><span class="sh">'</span><span class="s">users.urls</span><span class="sh">'</span><span class="p">)),</span>
<span class="nf">re_path</span><span class="p">(</span><span class="sa">r</span><span class="sh">'</span><span class="s">^search/(?P<year>[0-9]{4})/$</span><span class="sh">'</span><span class="p">,</span> <span class="n">search_by_year</span><span class="p">),</span>
<span class="nf">re_path</span><span class="p">(</span><span class="sa">r</span><span class="sh">'</span><span class="s">^search/(?P<keyword>\w+)/$</span><span class="sh">'</span><span class="p">,</span> <span class="n">search_by_keyword</span><span class="p">),</span>
<span class="p">]</span>
</pre></td></tr></tbody></table></code></div></div>
<ul>
<li><code class="language-plaintext highlighter-rouge">path("", index)</code> : 아무 url을 입력하지 않았을 경우 index 함수 실행</li>
<li><code class="language-plaintext highlighter-rouge">path("videos/<video_id>/", video)</code> : <code class="language-plaintext highlighter-rouge">videos/문자열/</code> 형태의 입력을 받았을 때 <아무 문자="">를 `video_id` 변수에 담아 video 함수 실행</아무></li>
<li><code class="language-plaintext highlighter-rouge">path("user/", include('users.urls'))</code> : <code class="language-plaintext highlighter-rouge">user/</code> url 요청을 받았을 때 users 폴더의 urls.py에서 처리하도록 지정</li>
<li><code class="language-plaintext highlighter-rouge">re_path(r'^search/(?P<year>[0-9]{4})/$', search_by_year)</code> : <code class="language-plaintext highlighter-rouge">search/<4자리 숫자>/</code> 형태의 입력을 받았다면 4자리 숫자를 <code class="language-plaintext highlighter-rouge">year</code> 변수에 담아 search_by_year 함수 실행</li>
</ul>
<h3 id="view와-연결"><span class="me-2">view와 연결</span><a href="#view와-연결" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<p>기본적으로 장고에서 <code class="language-plaintext highlighter-rouge">urls.py</code>에서 호출되어 실행하는 함수들은 <code class="language-plaintext highlighter-rouge">views.py</code>라는 별도 파일에서 관리한다. (MVT 모델 참고)</p>
<p>이를 위해 <code class="language-plaintext highlighter-rouge">views.py</code>를 import 하여, view에 선언된 함수들과 연결하는 방식을 취한다.</p>
<div class="language-python highlighter-rouge"><div class="code-header">
<span data-label-text="Python"><i class="fas fa-code fa-fw small"></i></span>
<button aria-label="copy" data-title-succeed="Copied!"><i class="far fa-clipboard"></i></button></div><div class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
</pre></td><td class="rouge-code"><pre><span class="n">jango는</span> <span class="n">view를</span> <span class="n">사용해</span> <span class="n">클라</span>
</pre></td></tr></tbody></table></code></div></div>
<blockquote>
<h4 id="번외--args--unpacking"><span class="me-2">번외 : **args : unpacking</span><a href="#번외--args--unpacking" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h4>
<p>딕셔너리 형태의 변수를 전달할 때 앞에 별표 2개를 붙여서 전달하면 딕셔너리를 풀어서 전달할 수 있다.
ex)</p>
<div class="language-python highlighter-rouge"><div class="code-header">
<span data-label-text="Python"><i class="fas fa-code fa-fw small"></i></span>
<button aria-label="copy" data-title-succeed="Copied!"><i class="far fa-clipboard"></i></button></div><div class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="rouge-code"><pre><span class="n">args</span> <span class="o">=</span> <span class="p">{</span><span class="err">’</span><span class="n">a</span><span class="err">’</span> <span class="p">:</span> <span class="err">‘</span><span class="n">hello</span><span class="err">’</span><span class="p">,</span> <span class="err">‘</span><span class="n">b</span><span class="err">’</span> <span class="p">:</span> <span class="err">‘</span><span class="n">world</span><span class="err">’</span><span class="p">}</span>
<span class="nf">foo</span><span class="p">(</span><span class="n">args</span><span class="p">[</span><span class="err">’</span><span class="n">a</span><span class="err">’</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="err">’</span><span class="n">b</span><span class="err">’</span><span class="p">])</span>
<span class="nf">foo</span><span class="p">(</span><span class="o">**</span><span class="n">args</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></div> </div>
<p>두 foo 함수는 는 동일하게 작동한다.</p>
</blockquote>
<h3 id="정리"><span class="me-2">정리</span><a href="#정리" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li>라우팅은 url path와 함수를 연결한다.</li>
<li>경로의 일부를 파라미터로 함수에 전달하는 방법이 있다.</li>
<li>함수는 사용자에게 전송할 문자열(HTML 코드 등)을 완성해서 응답한다.</li>
</ul>
<h2 id="view-viewspy"><span class="me-2">View (views.py)</span><a href="#view-viewspy" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h2>
<h3 id="view의-동작"><span class="me-2">View의 동작</span><a href="#view의-동작" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<div class="language-python highlighter-rouge"><div class="code-header">
<span data-label-text="Python"><i class="fas fa-code fa-fw small"></i></span>
<button aria-label="copy" data-title-succeed="Copied!"><i class="far fa-clipboard"></i></button></div><div class="highlight"><code><table class="rouge-table"><tbody><tr><td class="rouge-gutter gl"><pre class="lineno">1
2
3
4
5
</pre></td><td class="rouge-code"><pre><span class="c1"># views.py
</span><span class="kn">from</span> <span class="n">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="c1"># urls.py에서 views.index가 실행될 경우 아래 페이지가 실행됨
</span><span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
<span class="k">return</span> <span class="nc">HttpResponse</span><span class="p">(</span><span class="sh">"</span><span class="s">hello</span><span class="sh">"</span><span class="p">)</span>
</pre></td></tr></tbody></table></code></div></div>
<ul>
<li>Django는 view를 사용해 클라이언트의 요청을 처리하고, 응답을 만들어 반환한다.</li>
<li>view에는 두가지 종류가 있다.
<ul>
<li>Function-Based View : 함수로 구현한 뷰
<ul>
<li>간단하고 직관적이지만, 대부분의 구현을 직접해야한다.</li>
</ul>
</li>
<li>Class-Based View : 클래스로 구현한 뷰
<ul>
<li>패턴화 된 뷰 구조를 쉽게 구현한다.</li>
<li>높은 추상화로 구조나 코드의 이해가 어렵다.</li>
</ul>
</li>
<li>이번 과정에서는 Function-Based View만 다룰 것이다. 이를 잘 다룰 수 있어야 나중에 Class-Based View 도 잘 다룰 수 있다.</li>
</ul>
</li>
</ul>
<h3 id="response-함수의-종류"><span class="me-2">Response 함수의 종류</span><a href="#response-함수의-종류" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li>HttpResponse: 문자열 형식의 응답 반환</li>
<li>JsonResponse: JSON 형식의 응답 반환</li>
<li>HttpResponseRedirect : 다른 url 주소로 이동시킴 (Redirect)</li>
<li>HttpResponseNotFound : 404 Not Found 에러를 응답</li>
</ul>
<h3 id="requests의-종류"><span class="me-2">Requests의 종류</span><a href="#requests의-종류" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h3>
<ul>
<li>GET : url을 통해 정보를 담아 전송 (쿼리 스트링)
<ul>
<li>보안에 취약하다는 단점이 있다.</li>
<li>보통 유저가 얻고 싶은 정보를 필터링하기 위해 사용한다.</li>
</ul>
</li>
<li>POST : 요청 데이터의 body 부분에 데이터를 담아 전송한다.
<ul>
<li>데이터가 직접적으로 노출되지 않고 암호화를 통해 데이터를 보호할 수 있다.</li>
</ul>
</li>
<li>PUT, PUSH, DELETE 등 다른 방식도 존재한다.</li>
</ul>
<h4 id="django에서-request를-받는-방법"><span class="me-2">Django에서 Request를 받는 방법</span><a href="#django에서-request를-받는-방법" class="anchor text-muted"><i class="fas fa-hashtag"></i></a></h4>
<ul>
<li>GET 방식 : <code class="language-plaintext highlighter-rouge">req.GET</code>
<ul>
<li>GET 메소드로 전송된 쿼리스트링을 딕셔너리 형태로 반환한다.</li>
<li>예를 들어 <code class="language-plaintext highlighter-rouge">?q=hello&a=bye</code> 형식으로 입력된 쿼리가 있다면 <code class="language-plaintext highlighter-rouge">print(req.GET)</code>로 정보를 받았을 때 <code class="language-plaintext highlighter-rouge">{q:hello, a:bye}</code>이 반환된다.</li>
</ul>
</li>
<li>POST 방식 : <code class="language-plaintext highlighter-rouge">req.POST</code>
<ul>
<li>GET과 마찬가지로 딕셔너리를 반환하므로, GET 방식과 동일하게 body에 담긴 정보를 가져올 수 있다.</li>
</ul>
</li>
</ul>
</div>
<div class="post-tail-wrapper text-muted">
<!-- categories -->
<!-- tags -->
<div
class="
post-tail-bottom
d-flex justify-content-between align-items-center mt-5 pb-2
"
>
<div class="license-wrapper">
This post is licensed under
<a href="https://creativecommons.org/licenses/by/4.0/">
CC BY 4.0
</a>
by the author.
</div>
<!-- Post sharing snippet -->
<div class="share-wrapper d-flex align-items-center">
<span class="share-label text-muted">Share</span>
<span class="share-icons">
<a href="https://twitter.com/intent/tweet?text=Aivle%20Til%20230510%20Django%201%20-%20cjkangme%20Devlog&url=https%3A%2F%2Fcjkangme.github.io%2Fposts%2Faivle-til-230510-django-1%2F" target="_blank" rel="noopener" data-bs-toggle="tooltip" data-bs-placement="top" title="Twitter" aria-label="Twitter">
<i class="fa-fw fa-brands fa-square-x-twitter"></i>
</a>
<a href="https://www.facebook.com/sharer/sharer.php?title=Aivle%20Til%20230510%20Django%201%20-%20cjkangme%20Devlog&u=https%3A%2F%2Fcjkangme.github.io%2Fposts%2Faivle-til-230510-django-1%2F" target="_blank" rel="noopener" data-bs-toggle="tooltip" data-bs-placement="top" title="Facebook" aria-label="Facebook">
<i class="fa-fw fab fa-facebook-square"></i>
</a>
<a href="https://t.me/share/url?url=https%3A%2F%2Fcjkangme.github.io%2Fposts%2Faivle-til-230510-django-1%2F&text=Aivle%20Til%20230510%20Django%201%20-%20cjkangme%20Devlog" target="_blank" rel="noopener" data-bs-toggle="tooltip" data-bs-placement="top" title="Telegram" aria-label="Telegram">
<i class="fa-fw fab fa-telegram"></i>
</a>
<button
id="copy-link"
aria-label="Copy link"
class="btn small"
data-bs-toggle="tooltip"
data-bs-placement="top"
title="Copy link"
data-title-succeed="Link copied successfully!"
>
<i class="fa-fw fas fa-link pe-none fs-6"></i>
</button>
</span>
</div>
</div>
<!-- .post-tail-bottom -->
</div>
<!-- div.post-tail-wrapper -->
</article>
</main>
<!-- panel -->
<aside aria-label="Panel" id="panel-wrapper" class="col-xl-3 ps-2 text-muted">
<div class="access">
<!-- Get 5 last posted/updated posts -->
<section id="access-lastmod">
<h2 class="panel-heading">Recently Updated</h2>
<ul class="content list-unstyled ps-0 pb-1 ms-1 mt-2">
<li class="text-truncate lh-lg">
<a href="/posts/2023-02-11-til-%EC%9E%90%EC%9C%A0%EB%8F%84%EA%B0%80-%EB%AD%90%EC%A7%80/"></a>
</li>
<li class="text-truncate lh-lg">
<a href="/posts/2023-02-11-%EB%B0%B1%EC%A4%80-16947-%EC%84%9C%EC%9A%B8-%EC%A7%80%ED%95%98%EC%B2%A0-2%ED%98%B8%EC%84%A0-%ED%8C%8C%EC%9D%B4%EC%8D%AC/"></a>
</li>
<li class="text-truncate lh-lg">
<a href="/posts/2023-02-18-%EB%B0%B1%EC%A4%80-16964-dfs-%EC%8A%A4%ED%8E%98%EC%85%9C-%EC%A0%80%EC%A7%80-%ED%8C%8C%EC%9D%B4%EC%8D%AC/"></a>
</li>
<li class="text-truncate lh-lg">
<a href="/posts/2023-02-19-til-%ED%81%AC%EB%A3%A8%EC%8A%A4%EC%B9%BC-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98/"></a>
</li>
<li class="text-truncate lh-lg">
<a href="/posts/2023-02-25-%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-%EC%96%B8%EB%8D%94%EC%83%98%ED%94%8C%EB%A7%81%EA%B3%BC-%EC%98%A4%EB%B2%84%EC%83%98%ED%94%8C%EB%A7%81/"></a>
</li>
</ul>
</section>
<!-- #access-lastmod -->
<!-- The trending tags list -->
<section>
<h2 class="panel-heading">Trending Tags</h2>
<div class="d-flex flex-wrap mt-3 mb-1 me-3">
<a class="post-tag btn btn-outline-primary" href="/tags/javascript/">javascript</a>
<a class="post-tag btn btn-outline-primary" href="/tags/react/">react</a>
<a class="post-tag btn btn-outline-primary" href="/tags/ai/">ai</a>
<a class="post-tag btn btn-outline-primary" href="/tags/aivle/">aivle</a>
<a class="post-tag btn btn-outline-primary" href="/tags/cs231a/">cs231a</a>
<a class="post-tag btn btn-outline-primary" href="/tags/cv/">cv</a>
<a class="post-tag btn btn-outline-primary" href="/tags/%ED%9B%84%EA%B8%B0/">후기</a>
<a class="post-tag btn btn-outline-primary" href="/tags/%EC%BB%A8%ED%8D%BC%EB%9F%B0%EC%8A%A4/">컨퍼런스</a>
<a class="post-tag btn btn-outline-primary" href="/tags/dan24/">dan24</a>
<a class="post-tag btn btn-outline-primary" href="/tags/nerf/">nerf</a>
</div>
</section>
</div>
<div class="toc-border-cover z-3"></div>
<section id="toc-wrapper" class="invisible position-sticky ps-0 pe-4 pb-4">
<h2 class="panel-heading ps-3 pb-2 mb-0">Contents</h2>
<nav id="toc"></nav>
</section>
</aside>
</div>
<div class="row">
<!-- tail -->
<div id="tail-wrapper" class="col-12 col-lg-11 col-xl-9 px-md-4">
<!-- Recommend the other 3 posts according to the tags and categories of the current post. -->
<!-- The total size of related posts -->
<!-- An random integer that bigger than 0 -->
<!-- Equals to TAG_SCORE / {max_categories_hierarchy} -->
<!-- Navigation buttons at the bottom of the post. -->
<nav class="post-navigation d-flex justify-content-between" aria-label="Post Navigation">
<a
href="/posts/aivle-til-230509-sql-2/"
class="btn btn-outline-primary"
aria-label="Older"
>
<p>Aivle Til 230509 Sql 2</p>
</a>
<a
href="/posts/aivle-til-230512-django-3/"
class="btn btn-outline-primary"
aria-label="Newer"
>
<p>Aivle Til 230512 Django 3</p>
</a>
</nav>
<!-- The Footer -->
<footer
aria-label="Site Info"
class="
d-flex flex-column justify-content-center text-muted
flex-lg-row justify-content-lg-between align-items-lg-center pb-lg-3
"
>
<p>©
<time>2024</time>
<a href="https://github.com/cjkangme">Changjin Kang</a>.
<span
data-bs-toggle="tooltip"
data-bs-placement="top"
title="Except where otherwise noted, the blog posts on this site are licensed under the Creative Commons Attribution 4.0 International (CC BY 4.0) License by the author."
>Some rights reserved.</span>
</p>
<p>Using the <a
data-bs-toggle="tooltip"
data-bs-placement="top"
title="v7.2.2"
href="https://github.com/cotes2020/jekyll-theme-chirpy"
target="_blank"
rel="noopener"
>Chirpy</a> theme for <a href="https://jekyllrb.com" target="_blank" rel="noopener">Jekyll</a>.
</p>
</footer>
</div>
</div>
<!-- The Search results -->
<div id="search-result-wrapper" class="d-flex justify-content-center d-none">
<div class="col-11 content">
<div id="search-hints">
<!-- The trending tags list -->
<section>
<h2 class="panel-heading">Trending Tags</h2>
<div class="d-flex flex-wrap mt-3 mb-1 me-3">
<a class="post-tag btn btn-outline-primary" href="/tags/javascript/">javascript</a>
<a class="post-tag btn btn-outline-primary" href="/tags/react/">react</a>
<a class="post-tag btn btn-outline-primary" href="/tags/ai/">ai</a>
<a class="post-tag btn btn-outline-primary" href="/tags/aivle/">aivle</a>
<a class="post-tag btn btn-outline-primary" href="/tags/cs231a/">cs231a</a>
<a class="post-tag btn btn-outline-primary" href="/tags/cv/">cv</a>
<a class="post-tag btn btn-outline-primary" href="/tags/%ED%9B%84%EA%B8%B0/">후기</a>
<a class="post-tag btn btn-outline-primary" href="/tags/%EC%BB%A8%ED%8D%BC%EB%9F%B0%EC%8A%A4/">컨퍼런스</a>
<a class="post-tag btn btn-outline-primary" href="/tags/dan24/">dan24</a>
<a class="post-tag btn btn-outline-primary" href="/tags/nerf/">nerf</a>
</div>
</section>
</div>
<div id="search-results" class="d-flex flex-wrap justify-content-center text-muted mt-3"></div>
</div>
</div>
</div>
<aside aria-label="Scroll to Top">
<button id="back-to-top" type="button" class="btn btn-lg btn-box-shadow">
<i class="fas fa-angle-up"></i>
</button>
</aside>
</div>
<div id="mask" class="d-none position-fixed w-100 h-100 z-1"></div>
<aside
id="notification"
class="toast"
role="alert"
aria-live="assertive"
aria-atomic="true"
data-bs-animation="true"
data-bs-autohide="false"
>
<div class="toast-header">
<button
type="button"
class="btn-close ms-auto"
data-bs-dismiss="toast"
aria-label="Close"
></button>
</div>
<div class="toast-body text-center pt-0">
<p class="px-2 mb-3">A new version of content is available.</p>
<button type="button" class="btn btn-primary" aria-label="Update">
Update
</button>
</div>
</aside>
<!-- Embedded scripts -->
<!-- The comments switcher -->
<script>
var disqus_config = function () {
this.page.url = 'https://cjkangme.github.io/posts/aivle-til-230510-django-1/';
this.page.identifier = '/posts/aivle-til-230510-django-1/';
};
function addDisqus() {
let disqusThread = document.createElement('div');
let paragraph = document.createElement('p');
disqusThread.id = 'disqus_thread';
paragraph.className = 'text-center text-muted small';
paragraph.innerHTML = 'Comments powered by <a href="https://disqus.com/">Disqus</a>.';
disqusThread.appendChild(paragraph);
const footer = document.querySelector('footer');
footer.insertAdjacentElement("beforebegin", disqusThread);
}function reloadDisqus(event) {
if (event.source === window && event.data && event.data.id === Theme.ID) {if (typeof DISQUS === 'undefined') {
return;
}
if (document.readyState == 'complete') {
DISQUS.reset({ reload: true, config: disqus_config });
}
}
}
addDisqus();
if (Theme.switchable) {
addEventListener('message', reloadDisqus);
}var disqusObserver = new IntersectionObserver(
function (entries) {
if (entries[0].isIntersecting) {
var d = document,
s = d.createElement('script');
s.src = 'https://cjkangme.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
disqusObserver.disconnect();
}
},
{ threshold: [0] }
);
disqusObserver.observe(document.getElementById('disqus_thread'));
</script>
<!--
Jekyll Simple Search loader
See: <https://github.com/christian-fei/Simple-Jekyll-Search>
-->
<script>
document.addEventListener('DOMContentLoaded', () => {
SimpleJekyllSearch({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('search-results'),
json: '/assets/js/data/search.json',
searchResultTemplate: ' <article class="px-1 px-sm-2 px-lg-4 px-xl-0"> <header> <h2><a href="{url}">{title}</a></h2> <div class="post-meta d-flex flex-column flex-sm-row text-muted mt-1 mb-1"> {categories} {tags} </div> </header> <p>{snippet}</p> </article>',
noResultsText: '<p class="mt-5">Oops! No results found.</p>',
templateMiddleware: function(prop, value, template) {
if (prop === 'categories') {
if (value === '') {
return `${value}`;
} else {
return `<div class="me-sm-4"><i class="far fa-folder fa-fw"></i>${value}</div>`;
}
}
if (prop === 'tags') {
if (value === '') {
return `${value}`;
} else {
return `<div><i class="fa fa-tag fa-fw"></i>${value}</div>`;
}
}
}
});
});
</script>
</body>
</html>
</p>
</body>
</html>
blog/post/2/
도메인으로 이동하면 해당 id의 데이터를 받아올 수 있다.
ORM QuerySet 조회 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# title에 This가 포함된 post 추출
Post.objects.all().filter(title__contains='This')
# title에 This가 포함된 post 제외
Post.objects.all().exclude(title__contains='This')
# 여러 조건으로 조회: 아래와 같이 여러 조건을 걸어 데이터를 조회할 수 있다.
Post.objects.filter(title__contains='this', title__endswith='title')
Post.objects.filter(title__contains='this').filter(title__endswith='title')
# or and 연산자 사용
from django.db.models import Q
Post.objects.filter(Q(title__contains='this') | Q(title__endswith='title'))
Post.objects.filter(Q(title__contains='this') & Q(title__endswith='title'))
# title에 대소문자 구분 없이 this가 포함된 post 추출
Post.objects.filter(title__icontains=’this’)
# title이 this로 시작하는/끝나는 post 추출
Post.objects.filter(title__startswith=’This’)
Post.objects.filter(title__endswith=’title’)
# id가 1, 2, 3인 post 추출
Post.objects.filter(id__in=[ 1, 2, 3])
# id가 1~9인 post 추출
Post.objects.filter(id__range=( 1,10))
# 날짜 관련
Post.objects.filter(published_at__lt=timezone.now())
Post.objects.filter(published_at__gte=timezone.now())
Post.objects.filter(created_at__year=’ 2019’)
Post.objects.filter(created_at__month=’ 5’)
Post.objects.filter(created_at__day=’ 21’)
Post.objects.filter(published_at__isnull= True)
- filter에서 컬럼명과 필터 이름을 묶을때 언더바 2개를 사용한다는 것에 주의하자.