การสร้าง Model
แก้ไขไฟล์ models.py ที่ Application1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length = 264 , unique = True ) def __str__( self ): return self .top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length = 264 , unique = True ) url = models.URLField(unique = True ) def __str__( self ): return self .name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() def __str__( self ): return str ( self .date) # return value on admin interface |
เสร็จแล้วสั่ง migrate และ makemigrations และ migrate อีกรอบ
1 2 3 | python manage.py migrate python manage.py makemigrations first_app python manage.py migrate |
ทดสอบ Model โดยการใช้ Python Shell
1 | python manage.py shell |
1 2 3 4 5 6 7 | from first_app.models import Topic print (Topic.objects. all ()) t = Topic(top_name = "Social Network" ) t.save() print (Topic.objects. all ()) quit() |
การใช้งาน Admin Interface ของ django 1.10
แก้ไขไฟล์ admin ที่ Application
1 2 3 4 5 6 7 | from django.contrib import admin from first_app.models import AccessRecord, Topic, Webpage # Register your models here. admin.site.register(AccessRecord) admin.site.register(Topic) admin.site.register(Webpage) |
1 2 3 |
การเรียกขึ้นมาใช้ใน Template (Model Template View)
แก้ไขไฟล์ urls.py เพื่อเพิ่ม url และแก้ไขไฟล์ views.py โดยจะดึงค่าจากไฟล์นี้1 2 3 4 5 | ... urlpatterns = [ ... url(r '^model' , views.model, name = 'model' ) ] |
1 2 3 4 5 6 7 8 9 | ... from first_app.models import AccessRecord, Topic, Webpage ... def model(request): webpages_list = AccessREcord.objects.order_by( 'date' ) data_dict = { 'access_records' : webpage_list} return render(request, 'first_app/model.html' , context = data_dict) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | ... < div class = "django" > {% if access_records %} < table > < thead > < th >Site Name</ th > < th >Date Accessed</ th > </ thead > < tbody > {% for acc in access_records %} < tr > < td >{{ acc.name }}</ td > < td >{{ acc.date }}</ td > </ tr > {% endfor %} </ tbody > </ table > {% else %} < p >No Access Records Found!</ p > {% endif %} </ div > ... |
ไม่มีความคิดเห็น:
แสดงความคิดเห็น