Python Django
Python Django 15 - ORM(DB) 사용 예제(필드 타입 명령)
코딩탕탕
2022. 10. 23. 14:50

urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.main),
path("show", views.show),
]
views.py
from django.shortcuts import render
from myapp.models import Article
def main(request):
return render(request, 'main.html')
def show(request):
# sql = "select * from Article"
datas = Article.objects.all() # Django ORM
print(datas)
print(datas[0].name)
return render(request, 'list.html', {'articles':datas})
models.py에서 만든 database를 datas라는 변수명에 넣고 그것을 dict 타입으 list.html로 가져가고 있다.
admin.py
from django.contrib import admin
from myapp.models import Article
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
list_display = ('id','code','name','price','pub_date')
admin.site.register(Article, ArticleAdmin)
models.py
from django.db import models
# Create your models here.
# Database Table을 class로 선언
class Article(models.Model):
code = models.CharField(max_length = 10)
name = models.CharField(max_length = 20)
price = models.IntegerField()
pub_date = models.DateField()
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>메인</p>
메뉴1 메뉴2 <a href="show">자료보기</a>
</body>
</html>
list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
{% extends 'layout.html' %}
{% block content %}
<p>Article 데이터 출력</p>
{% if articles.count > 0 %}
{% for a in articles %}
<b>{{a.code}}</b> {{a.name}} {{a.price}} {{a.pub_date}} <br />
{% endfor %}
{% else %}
<p>자료 없음</p>>
{% endif %}
{% endblock %}
</body>
</html>
layout.html
<h2>** 자료 보기 **</h2>
<div style="color:blue;">
{% block content %}
{% endblock %}
</div>
layout.html 이라는 파일을 만들어서 원하는 곳에 include 할 수 있다.