はじめに
普段はRailsを書くことが多いのですが、たまにDjangoを触った時に毎回コマンドやら記法を忘れるので、自分の備忘録のために、RailsとDjangoで近しいコマンドや記法をまとめました。
出会ったタイミングで追記していきます。
開発
Django(Python) | Rails(ruby) | |
---|---|---|
開発サーバの起動 | python manage.py runserver |
rails s rails server
|
開発サーバの起動(port指定) | python manage.py runserver 8080 |
rails s -p 8080 |
consoleの起動 |
python manage.py shell もろもろimportしておきたい場合: python manage.py shell_plus
|
rails c rails console
|
使用できるコマンドの一覧 |
python manage.py => management/commands/hogehoge.py
|
rake -vT rake taskは lib/tasks 以下に追加 |
コマンドの実行 | python manage.py hogehoge |
rake hogehoge |
URLの表示 |
pip install django-extensions settings.pyに INSTALLED_APPS += ('django_extensions', ) python manage.py show_urls
|
rake routes |
inspect | # python manage.py shell実行したのちimport inspect q = Question.objects.get(id=1) inspect.getmembers(q)
|
# pry gemを利用 # rails consoleを実行したのち q = Question.find(1) q.inspect ls q
|
データベース関連
Django(Python) | Rails(ruby) | |
---|---|---|
migrationファイルの作成 | python manage.py makemigrations |
rails g migration |
migrationの実行 | python manage.py migrate |
rake db:migrate rails db:migrate # Rails 5以上
|
データベースへ接続 | python manage.py dbshell |
rails db |
ER図の自動生成 | 記事 | 記事 |
レコードへのアクセス
Django(Python) | Rails(ruby) | |
---|---|---|
レコード全取得 | Question.objects.all() |
Question.all |
インスタンス化して保存 |
q = Question(question_text="What's new?", pub_date=timezone.now()) q.save()
|
q = Question.new(question_text: "What's new?", pub_date: Time.current) q.save!
|
リレーションをはったレコードの作成 | リレーションは*_set を使う。q.choice_set.create(choice_text='The sky', votes=0)
|
Questionモデルにhas_many :choices とし、q.choices.create!(choice_text: 'The sky', votes: 0)
|
リレーションをはったレコードの全取得 | q.choice_set.all() |
q.choices |
リレーションをはったレコードの件数取得 | q.choice_set.count() |
q.choices.count |
# 条件を指定してレコードを取得
Django(Python) | Rails(ruby) |
---|---|
Question.objects.filter(id=1) |
Question.where(id: 1) |
Question.objects.filter(question_text__startswith='What') |
Question.where("question_text like ?", "What%") |
Question.objects.get(id=2) |
Question.find(2) |
Choice.objects.filter(question__pub_date__year=current_year) |
Choice.where(question: Question.where(pub_date: Time.current.beginning_of_year..Time.current.end_of_year)) |
Choice.objects.get_or_create(id=1) |
Choice.find_or_create_by(id: 1) |
テスト実行
Django(Python) | Rails(ruby) |
---|---|
python manage.py test |
rspec spec/ # specの場合 rails test/ # rails 5以上。minitestの場合
|
その他
継承
Django
class QuestionModelTests(TestCase):
Rails
class QuestionModelTests < TestCase