簡易博客開發(2)----models, admin

django提供了很是方便的數據模型,能夠很是簡易的設計時間結構,URL結構,輸入框等等,django都已經有編寫好的數據結構,對於我這種初級編程來講再好沒有,不然我就要本身寫數據約束,格式,出錯等 python

對於一個博客系統最基本包含三個要素,「做者」, 「博客」,「標籤」 linux

#/myblog/myblog/blog/models.py
  1 from django.db import models                                                                          
  2                                                                                                       
  3 # Create your models here.                                                                            
  4                                                                                                       
  5 class Author(models.Model):                                          #做者信息                                                                       
  6     """docstring for Author"""                                                                        
  7     name = models.CharField(max_length=30)                                                            
  8     email = models.EmailField(blank=True)                                                             
  9     website = models.URLField(blank=True)                                                             
 10                                                                                                       
 11     def __unicode__(self):                                           #方便查詢時返回一個名字,不然是一個實例                                 
 12         return self.name                                                                              
 13                                                                                                       
 14 class Tag(models.Model):                                             #標籤                                                                           
 15     """tag of book"""                                                                                 
 16     tag_name = models.CharField(max_length = 30)                                                      
 17     create_time = models.DateTimeField(auto_now_add =True )                                           
 18                                                                                                       
 19     def __unicode__(self):                                                                            
 20         return self.tag_name                                                                          
 21                                                                                                       
 22 class blog(models.Model):                                            #博客                                 
 23     title = models.CharField(max_length=50)                          #標題                                 
 24     author = models.ForeignKey(Author)                               #做者 做者與博客是一對多的關係,一個博客只有一個做者,一個做者能夠有多個博客                                
 25     tags = models.ManyToManyField(Tag, blank=True)                   #標籤 標籤與博客是多對多的關係,一個博客有多個標籤,一個標籤也能夠有多個博客,所以初始化時不能直接賦值,它是一個列表                                
 26     content = models.TextField()                                     #內容                                 
 27     date_time = models.DateTimeField(auto_now_add = True)                                             
 28                                                                                                       
 29     def __unicode__(self):                                                                            
 30         return self.title                                                                             
 31                                                                                                       
 32     class Meta:                                                                                       
 33         ordering = ['-date_time']                                    #按照時間排序                                 
 34                                       
 

後臺所對應的數據結構 web

同步數據庫 shell

[root@hding myblog]# python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
django 1.8.8 與 django 1.6 之前在models的重大改變在於若是你更改了數據庫中的字段,你能夠經過makemigrations更改,而在1.6之前一旦syncdb以後若是還須要加字段則只能在數據庫中經過SQL語方直接進行操做,不能經過django實現,如如今把類blog改爲類Blog
[root@hding myblog]# python manage.py  makemigrations
Migrations for 'blog':
  0001_initial.py:
    - Create model Author
    - Create model Blog
    - Create model Tag
    - Add field tags to blog
[root@hding myblog]# python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, blog, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying blog.0001_initial... OK

數據在shell中的調試 數據庫

[root@hding myblog]# python manage.py shell
Python 2.7.11 (default, Feb  4 2016, 07:16:42) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from blog.models import Blog
>>> from blog.models import Author
>>> from blog.models import Tag
#增長建立數據
>>> author_1 = Author.objects.create(name ='terry') 
>>> author_1
<Author: terry>
>>> tag_1 = Tag.objects.create(tag_name='python')
>>> tag_1
<Tag: python>
>> blog_1 = Blog.objects.create(title = 'hello world',
...                              author = author_1,
...                              content = 'this is a first web site for me')
>>> blog_1
<Blog: hello world>
>>> blog_1.tags.all()
[]
#給blog 增長tag
>>> blog_1.tags.add(tag_1)
>>> blog_1.tags.all()
[<Tag: python>]
>>> blog_1.date_time
datetime.datetime(2016, 2, 10, 7, 43, 2, 448507, tzinfo=<UTC>)              #時間自動添加
#簡易建立方法直接對象實例化,但必需save,不然沒有寫進數據庫,而用Author.objects.create()則是直接寫到數據庫中
>>> author_2 = Author(name='sumsan')  
>>> author_2
<Author: sumsan>
>>> author_2.save()                                                         #必需save()才能確保寫進數據庫裏
#查詢單個數據和全部數據
>>> Author.objects.all()
[<Author: terry>, <Author: sumsan>]
>>> author= Author.objects.get(name='terry')                                #author爲查到的名字爲terry的實例
>>> author
<Author: terry>
>>> author_1
<Author: terry>
#建立由terry寫的第二個博客
>>> blog_2 = Blog.objects.create(title='django',author=author_1,content='django is so easy to use')
>>> Blog.objects.all()
[<Blog: hello world>, <Blog: django>]
#查詢terry寫的全部博客
>>> author_1.blog_set.all()
[<Blog: hello world>, <Blog: django>]
#查詢terry寫的博客中題目爲django的博客
>>> author_1.blog_set.get(title='django')
<Blog: django> 
#新建tag_2,tag_3
>>> tag_2 = Tag(tag_name='django')
>>> tag_2.save()
>>> tag_3 = Tag.objects.create(tag_name='socket')
>>> Tag.objects.all()
[<Tag: python>, <Tag: django>, <Tag: socket>]
#blog_1增長django標籤
>>> blog_1.tags.add(tag_2)
#blog_2增長django標籤
>>> blog_2.tags.add(tag_2)
#查詢含有django標籤的博客
>>> tag_2.blog_set.all()
[<Blog: hello world>, <Blog: django>]
#查詢blog_1含有的標籤
>>> blog_1.tags.all()     
[<Tag: python>, <Tag: django>]
#過濾查詢
>>> blog_1.tags.filter(tag_name__icontains='dj')
[<Tag: django>]
>>> blog_1.tags.filter(tag_name__iexact='django')
[<Tag: django>]
#刪除操做
>>> blog_1.tags.filter(tag_name__iexact='django').delete()
>>> blog_1.tags.filter(tag_name__iexact='django')
[]

在shell創建的數據在哪呢,能夠在django自定義的admin後臺看到 django

#新建超極用戶
[root@hding myblog]# python manage.py createsuperuser
Username (leave blank to use 'root'): root
Email address: root@a.com
Password: 
Password (again): 
Superuser created successfully.
修改admin.py,只有在後臺註冊了,才能在admin後臺進行管理

/myblog/myblog/blog/admin.py  
  1 from django.contrib import admin                                                                      
  2                                                                                                       
  3 # Register your models here.                                                                          
  4 from blog.models import Author,Tag,Blog                                                               
  5                                                                                                       
  6 class AuthorAdmin(admin.ModelAdmin):                     #定製Author界面                                                              
  7     list_display=('name','email','website')              #分爲name,email,website三列進行顯示                                             
  8     search_field=('name')                                                                             
  9                                                                                                       
 10 class BlogAdmin(admin.ModelAdmin):                       #定製Blog界面
 11     list_display = ('title','author','date_time')                                                     
 12     list_filter = ('date_time',)                         #按照時間進行查看                                                                                                                   
 15     filter_horizontal=('tags',)                          #tag水平選擇                                             
 16                                                                                                       
 17 admin.site.register(Author, AuthorAdmin)                 #註冊                                               
 18 admin.site.register(Blog,BlogAdmin)                                                                   
 19 admin.site.register(Tag)                                                                              
~
老界面

             

定製後的界面 編程

定製後的界面可以更加直觀的看到內部的數據,admin也是能夠自定義的,這是咱們管理後臺數據的地方,能夠經過admin對數據庫的數據進行增刪改查,更加方便 session

相關文章
相關標籤/搜索