Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Django Girls Advanced - Models: Level 2

Django Girls Advanced - Models: Level 2

Tzu-ping Chung

October 20, 2015
Tweet

More Decks by Tzu-ping Chung

Other Decks in Programming

Transcript

  1. SQL Database title content location My First Trip ᡙࢠ޷ծɼ٣ॄኄ޷䏆? ୆๺Րं᜾

    Django େ๯ᯃ ኺᯩଶ౸ಈଶ ୆๺ࢢେ҆ე෮ڵೆ࿏ Ұஈ293ᥒ … … …
  2. class Post(Model): title = CharField(max_length=100) abstract = CharField( max_length=100, blank=True)

    content = TextField(blank=True) location = CharField(max_length=100)
  3. >>> posts = Post.objects.all() >>> print(posts[0].abstract) Traceback (most recent call

    last): … django.db.utils.OperationalError: no such column: trips_post.abstract >>>
  4. trips ├── __init__.py ├── admin.py ├── migrations │ ├── 0001_initial.py

    │ ├── 0002_post_abstract.py │ └── __init__.py ├── models.py ├── tests.py └── views.py
  5. $ python manage.py migrate trips Operations to perform: Apply all

    migrations: trips Running migrations: Rendering model states... DONE Applying trips.0002_post_abstract... OK
  6. $ python manage.py makemigrations trips Migrations for 'trips': 0003_author.py: -

    Create model Author $ python manage.py migrate trips Operations to perform: Apply all migrations: trips Running migrations: Rendering model states... DONE Applying trips.0003_author... OK
  7. $ python manage.py makemigrations trips You are trying to add

    a non-nullable fi Please select a fix: 1) Provide a one-off default now (will 2) Quit, and let me add a default in m Select an option: _
  8. $ python manage.py makemigrations trips You are trying to add

    a non-nullable fi Please select a fix: 1) Provide a one-off default now (will 2) Quit, and let me add a default in m Select an option: 1 Please enter the default value now, as The datetime and django.utils.timezone >>> 1
  9. $ python manage.py makemigrations trips You are trying to add

    a non-nullable fi Please select a fix: 1) Provide a one-off default now (will 2) Quit, and let me add a default in m Select an option: 1 Please enter the default value now, as The datetime and django.utils.timezone >>> 1 Migrations for 'trips': 0004_post_author.py: - Add field author to post
  10. $ python manage.py migrate trips Operations to perform: Apply all

    migrations: trips Running migrations: Rendering model states... DONE Applying trips.0004_post_author... OK
  11. >>> from trips.models import Post >>> posts = Post.objects.all() >>>

    posts[0].author <Author: Django Girls Taipei> >>> posts[0].author.name 'Django Girls Taipei'
  12. Exercises • Add abstract field in Post • Add Author

    model • Add author foreign key in Post • Display author in template