03 - Models and the admin site

Models and the admin site

  1. Database setup

    $ pip install mysqlclient
    
  2. Creating models

    from django.db import models
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
  3. Include the app in our project

    INSTALLED_APPS = [
        'polls.apps.PollsConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
  4. Activating models

    # 生成遷移文件
    $ python manage.py makemigrations polls
    # 執(zhí)行指定遷移
    $ python manage.py migrate polls 0001
    # 執(zhí)行全部遷移
    $ python manage.py migrate
    
  5. Playing with the API

    # 進(jìn)入Database API
    $ python manage.py shell
    
    # Import the model classes we just wrote.
    >>> from polls.models import Choice, Question  
    
    # No questions are in the system yet.
    >>> Question.objects.all()
    <QuerySet []>
    
    # Create a new Question.
    # Support for time zones is enabled in the default settings file, so
    # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
    # instead of datetime.datetime.now() and it will do the right thing.
    >>> from django.utils import timezone
    >>> q = Question(question_text="What's new?", pub_date=timezone.now())
    
    # Save the object into the database. You have to call save() explicitly.
    >>> q.save()
    
    # Now it has an ID.
    >>> q.id
    1
    
    # Access model field values via Python attributes.
    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
    
    # Change values by changing the attributes, then calling save().
    >>> q.question_text = "What's up?"
    >>> q.save()
    
    # objects.all() displays all the questions in the database.
    >>> Question.objects.all()
    <QuerySet [<Question: Question object (1)>]>
    
    # 通過(guò)給polls/models.py 中的模型添加__str__()方法
    # 讓Question.objects.all()的調(diào)用顯示對(duì)于的值
    from django.db import models
    
    class Question(models.Model):
        # ...
        def __str__(self):
            return self.question_text
    
    class Choice(models.Model):
        # ...
        def __str__(self):
            return self.choice_text
    
    >>> from polls.models import Choice, Question
    
    # Make sure our __str__() addition worked.
    >>> Question.objects.all()
    <QuerySet [<Question: What's up?>]>
    
    # Django provides a rich database lookup API that's entirely driven by
    # keyword arguments.
    >>> Question.objects.filter(id=1)
    <QuerySet [<Question: What's up?>]>
    >>> Question.objects.filter(question_text__startswith='What')
    <QuerySet [<Question: What's up?>]>
    
    # Get the question that was published this year.
    >>> from django.utils import timezone
    >>> current_year = timezone.now().year
    >>> Question.objects.get(pub_date__year=current_year)
    <Question: What's up?>
    
    # Request an ID that doesn't exist, this will raise an exception.
    >>> Question.objects.get(id=2)
    Traceback (most recent call last):
        ...
    DoesNotExist: Question matching query does not exist.
    
    # Lookup by a primary key is the most common case, so Django provides a
    # shortcut for primary-key exact lookups.
    # The following is identical to Question.objects.get(id=1).
    >>> Question.objects.get(pk=1)
    <Question: What's up?>
    
    # Make sure our custom method worked.
    >>> q = Question.objects.get(pk=1)
    >>> q.was_published_recently()
    True
    
    # Give the Question a couple of Choices. The create call constructs a new
    # Choice object, does the INSERT statement, adds the choice to the set
    # of available choices and returns the new Choice object. Django creates
    # a set to hold the "other side" of a ForeignKey relation
    # (e.g. a question's choice) which can be accessed via the API.
    >>> q = Question.objects.get(pk=1)
    
    # Display any choices from the related object set -- none so far.
    >>> q.choice_set.all()
    <QuerySet []>
    
    # Create three choices.
    >>> q.choice_set.create(choice_text='Not much', votes=0)
    <Choice: Not much>
    >>> q.choice_set.create(choice_text='The sky', votes=0)
    <Choice: The sky>
    >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
    
    # Choice objects have API access to their related Question objects.
    >>> c.question
    <Question: What's up?>
    
    # And vice versa: Question objects get access to Choice objects.
    >>> q.choice_set.all()
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    >>> q.choice_set.count()
    3
    
    # The API automatically follows relationships as far as you need.
    # Use double underscores to separate relationships.
    # This works as many levels deep as you want; there's no limit.
    # Find all Choices for any question whose pub_date is in this year
    # (reusing the 'current_year' variable we created above).
    >>> Choice.objects.filter(question__pub_date__year=current_year)
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    
    # Let's delete one of the choices. Use delete() for that.
    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    
  6. Creating an admin user

    $ python manage.py createsuperuser
    Username: admin
    Email address: admin@example.com
    Password: **********
    Password (again): *********
    Superuser created successfully.
    
  7. Make the poll app modifiable in the admin

    # polls/admin.py
    from django.contrib import admin
    from .models import Question
    
    admin.site.register(Question)
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子脐恩,更是在濱河造成了極大的恐慌咆贬,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,332評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瓦灶,死亡現(xiàn)場(chǎng)離奇詭異烁登,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)易阳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,508評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門附较,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人潦俺,你說(shuō)我怎么就攤上這事拒课。” “怎么了事示?”我有些...
    開(kāi)封第一講書人閱讀 157,812評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵早像,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我肖爵,道長(zhǎng)卢鹦,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 56,607評(píng)論 1 284
  • 正文 為了忘掉前任遏匆,我火速辦了婚禮法挨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘幅聘。我一直安慰自己凡纳,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,728評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布帝蒿。 她就那樣靜靜地躺著荐糜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪葛超。 梳的紋絲不亂的頭發(fā)上暴氏,一...
    開(kāi)封第一講書人閱讀 49,919評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音绣张,去河邊找鬼答渔。 笑死,一個(gè)胖子當(dāng)著我的面吹牛侥涵,可吹牛的內(nèi)容都是我干的沼撕。 我是一名探鬼主播,決...
    沈念sama閱讀 39,071評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼芜飘,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼务豺!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起嗦明,我...
    開(kāi)封第一講書人閱讀 37,802評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤笼沥,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體奔浅,經(jīng)...
    沈念sama閱讀 44,256評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡馆纳,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,576評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了乘凸。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片厕诡。...
    茶點(diǎn)故事閱讀 38,712評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡累榜,死狀恐怖营勤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情壹罚,我是刑警寧澤葛作,帶...
    沈念sama閱讀 34,389評(píng)論 4 332
  • 正文 年R本政府宣布,位于F島的核電站猖凛,受9級(jí)特大地震影響赂蠢,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜辨泳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,032評(píng)論 3 316
  • 文/蒙蒙 一虱岂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧菠红,春花似錦第岖、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至遇绞,卻和暖如春键袱,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背摹闽。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,026評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工蹄咖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人付鹿。 一個(gè)月前我還...
    沈念sama閱讀 46,473評(píng)論 2 360
  • 正文 我出身青樓澜汤,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親倘屹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子银亲,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,606評(píng)論 2 350