Django : モデルの逆参照

DjangoはINSTALLED_APPSのモデルのERを解析するので、Foreign Keyで参照しているモデルのエンティティを逆(“reverse”)参照してくれます。

hoge データベース作成

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test$ ~/bin/MySQL/createdb.sh hoge
Distribution is Debian.
Apache is apache2.
SERVER=localhost DATABASE=hoge DBUSER=hoge DBPWD=hoge
hoge

hogesite プロジェクトを作ってhoge アプリを追加

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test$ django-admin.py startproject hogesite
(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test$ cd hogesite/
(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py startapp hoge

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ grep hoge settings.py
# Django settings for hogesite project.
DATABASE_NAME = ‘hoge’             # Or path to database file if using sqlite3.
DATABASE_USER = ‘hoge’             # Not used with sqlite3.
DATABASE_PASSWORD = ‘hoge’         # Not used with sqlite3.
ROOT_URLCONF = ‘hogesite.urls’

モデルを反映

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py syncdb
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site

You just installed Django’s auth system, which means you don’t have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use ‘hdknr’):
E-mail address: hdknr@hdknr.deb
Password:
Password (again):
Error: Your passwords didn’t match.
Password:
Password (again):
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Message model

id=1(admin)を参照

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py shell
imported django settings
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> u=User.objects.get(id=1)
>>> dir(u)
[‘DoesNotExist’, ‘MultipleObjectsReturned’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__eq__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__metaclass__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__unicode__’, ‘__weakref__’, ‘_base_manager’, ‘_collect_sub_objects’, ‘_default_manager’, ‘_deferred’, ‘_get_FIELD_display’, ‘_get_next_or_previous_by_FIELD’, ‘_get_next_or_previous_in_order’, ‘_get_pk_val’, ‘_meta’, ‘_set_pk_val’, ‘check_password’, ‘date_joined’, ‘delete’, ‘email’, ‘email_user’, ‘first_name’, ‘get_absolute_url’, ‘get_all_permissions’, ‘get_and_delete_messages’, ‘get_full_name’, ‘get_group_permissions’, ‘get_next_by_date_joined’, ‘get_next_by_last_login’, ‘get_previous_by_date_joined’, ‘get_previous_by_last_login’, ‘get_profile’, ‘groups’, ‘has_module_perms’, ‘has_perm’, ‘has_perms’, ‘has_usable_password’, ‘id’, ‘is_active’, ‘is_anonymous’, ‘is_authenticated’, ‘is_staff’, ‘is_superuser’, ‘last_login’, ‘last_name’, ‘message_set’, ‘objects’, ‘password’, ‘pk’, ‘prepare_database_save’, ‘save’, ‘save_base’, ‘serializable_value’, ‘set_password’, ‘set_unusable_password’, ‘user_permissions’, ‘username’]
>>>

1 : n でUserを参照するBlogモデルを定義

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ vi hoge/models.py

from django.db import models
from django.contrib.auth import models as auth_models

class Blog(models.Model):
    author = models.ForeignKey(auth_models.User)
    title = models.CharField(max_length=100)
    text  = models.TextField()

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ vi settings.py

INSTALLED_APPS = (
    ‘hoge’,
)
(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py syncdb
Creating table hoge_blog
Installing index for hoge.Blog model

Userをロードするとblog_set でBlogリストを逆参照できる

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py shell
imported django settings
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> u=User.objects.get(id=1)
>>> dir(u)
[‘DoesNotExist’, ‘MultipleObjectsReturned’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__eq__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__metaclass__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__unicode__’, ‘__weakref__’, ‘_base_manager’, ‘_collect_sub_objects’, ‘_default_manager’, ‘_deferred’, ‘_get_FIELD_display’, ‘_get_next_or_previous_by_FIELD’, ‘_get_next_or_previous_in_order’, ‘_get_pk_val’, ‘_meta’, ‘_set_pk_val’, ‘blog_set’, ‘check_password’, ‘date_joined’, ‘delete’, ‘email’, ‘email_user’, ‘first_name’, ‘get_absolute_url’, ‘get_all_permissions’, ‘get_and_delete_messages’, ‘get_full_name’, ‘get_group_permissions’, ‘get_next_by_date_joined’, ‘get_next_by_last_login’, ‘get_previous_by_date_joined’, ‘get_previous_by_last_login’, ‘get_profile’, ‘groups’, ‘has_module_perms’, ‘has_perm’, ‘has_perms’, ‘has_usable_password’, ‘id’, ‘is_active’, ‘is_anonymous’, ‘is_authenticated’, ‘is_staff’, ‘is_superuser’, ‘last_login’, ‘last_name’, ‘message_set’, ‘objects’, ‘password’, ‘pk’, ‘prepare_database_save’, ‘save’, ‘save_base’, ‘serializable_value’, ‘set_password’, ‘set_unusable_password’, ‘user_permissions’, ‘username’]

1:1で参照するProfileモデルを追加

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ vi hoge/models.py
class Profile(models.Model):
    user = models.OneToOneField(auth_models.User)
    mobile_email = models.CharField(max_length=100)
    twitter = models.CharField(max_length=100)

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py syncdb
Creating table hoge_profile

UserはprofileでProfileモデルを逆参照

(myrpx)hdknr@deblen2010:~/.ve/myrpx/src/test/hogesite$ python manage.py shell
imported django settings
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> u=User.objects.get(id=1)
>>> dir(u)
[‘DoesNotExist’, ‘MultipleObjectsReturned’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__eq__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__metaclass__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__unicode__’, ‘__weakref__’, ‘_base_manager’, ‘_collect_sub_objects’, ‘_default_manager’, ‘_deferred’, ‘_get_FIELD_display’, ‘_get_next_or_previous_by_FIELD’, ‘_get_next_or_previous_in_order’, ‘_get_pk_val’, ‘_meta’, ‘_set_pk_val’, ‘blog_set’, ‘check_password’, ‘date_joined’, ‘delete’, ‘email’, ‘email_user’, ‘first_name’, ‘get_absolute_url’, ‘get_all_permissions’, ‘get_and_delete_messages’, ‘get_full_name’, ‘get_group_permissions’, ‘get_next_by_date_joined’, ‘get_next_by_last_login’, ‘get_previous_by_date_joined’, ‘get_previous_by_last_login’, ‘get_profile’, ‘groups’, ‘has_module_perms’, ‘has_perm’, ‘has_perms’, ‘has_usable_password’, ‘id’, ‘is_active’, ‘is_anonymous’, ‘is_authenticated’, ‘is_staff’, ‘is_superuser’, ‘last_login’, ‘last_name’, ‘message_set’, ‘objects’, ‘password’, ‘pk’, ‘prepare_database_save’, ‘profile’, ‘save’, ‘save_base’, ‘serializable_value’, ‘set_password’, ‘set_unusable_password’, ‘user_permissions’, ‘username’]

カテゴリー: 未分類 パーマリンク

コメントを残す

以下に詳細を記入するか、アイコンをクリックしてログインしてください。

WordPress.com ロゴ

WordPress.com アカウントを使ってコメントしています。 ログアウト / 変更 )

Twitter 画像

Twitter アカウントを使ってコメントしています。 ログアウト / 変更 )

Facebook の写真

Facebook アカウントを使ってコメントしています。 ログアウト / 変更 )

Google+ フォト

Google+ アカウントを使ってコメントしています。 ログアウト / 変更 )

%s と連携中