django メモ

下書きの肥やしになっていたdjangoの試した時のメモ。

環境

software version
django 2.2.1

アプリケーションファイル

  • views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")
  • urls.py
from django.urls import path

from . import views

urlpatterns = [

urlpatterns = [
    path('',    # 設定した文字列がURLに表示される
         views.index,    
         name='index'),    # projectフォルダのurls.pyで指定する名前
]
]

モデルフィールド

リレーション先の特定のフィールドの値を取得する設定に苦戦した。

参考:

medium.com

stackoverflow.com

stackoverflow.com

k-mawa.hateblo.jp

docs.djangoproject.com

qiita.com

Django2.0から必須になったon_deleteの使い方 - Djangoの学習ができるチュートリアルサイトDjangoBrothers

トークン認証

simpleisbetterthancomplex.com

エラー対応

AttributeError

runserver実行時にエラーが発生した。

ubuntu@ip-10-0-1-180:~/django_rest_framework_test$ python3 manage.py runserver 0:8000
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check
    for pattern in self.url_patterns:
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 579, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/ubuntu/django_rest_framework_test/django_rest_framework_test/urls.py", line 20, in <module>
    from petstore.urls import router as petstore_router
  File "/home/ubuntu/django_rest_framework_test/petstore/urls.py", line 4, in <module>
    from .views import UserViewSet, PetViewSet
  File "/home/ubuntu/django_rest_framework_test/petstore/views.py", line 10, in <module>
    class UserViewSet(viewsets.ModelViewSet):
  File "/home/ubuntu/django_rest_framework_test/petstore/views.py", line 11, in UserViewSet
    queryset = User.Objects.all()
AttributeError: type object 'User' has no attribute 'Objects'

解決に必要な情報が末尾3行にある。

  File "/home/ubuntu/django_rest_framework_test/petstore/views.py", line 11, in UserViewSet
    queryset = User.Objects.all()
AttributeError: type object 'User' has no attribute 'Objects'

view.pyqueryset = User.Objects.all()を行ったが、オブジェクトUserObjectsは無いよ、という意味。 Objectsobjectsのタイポだったため修正して解決した。

You are trying to add a non-nullable field

複数のモデル間でリレーションを設定するため、models.py に新しいフィールドを追加。
migrate を実行するとYou are trying to add a non-nullable fieldのエラーを出力した。

ubuntu@ip-10-0-1-180:~/django_rest_framework_test$ python3 manage.py makemigrations
No changes detected
ubuntu@ip-10-0-1-180:~/django_rest_framework_test$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, petstore, sessions
Running migrations:
  No migrations to apply.
ubuntu@ip-10-0-1-180:~/django_rest_framework_test$ python3 manage.py makemigrations
You are trying to add a non-nullable field 'category' to pet without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:
Please select a valid option:

新しいフィールドの追加が既に登録したデータにも行われるがフィールドが空を許可していないため、何か値を入れるためのアクションしてね~という内容。

対応の一つとして、models に null=Trueを設定し空の場合はnullが入るようにすることで回避できる。

class Pet(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)

bad_value, referenced_table_name, referenced_column_name

リレーションを設定した項目が親のidの値を保持していたので、別のフィールド値を持たせたいと思い設定を変更した。 migrate 時にエラーが出力された。

ubuntu@ip-10-0-1-180:~/django_rest_framework_test$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, petstore, sessions
Running migrations:
  Applying petstore.0004_auto_20190514_1848...Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle
    fake_initial=fake_initial,
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 247, in apply_migration
    migration_recorded = True
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 34, in __exit__
    self.connection.check_constraints()
  File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 318, in check_constraints
    bad_value, referenced_table_name, referenced_column_name
django.db.utils.IntegrityError: The row in table 'petstore_pet' with primary key '1' has an invalid foreign key: petstore_pet.category contains a value '2' that does not have a corresponding value in petstore_category.name.
ubuntu@ip-10-0-1-180:~/django_rest_framework_test$

フィールドが対応しない形の値(変更前の値)を保持しているため、新しく保持しようとした値が入れられない。 エラーとなる値を削除することで回避可能。