GenericForeignKeyについてのメモ
GenericForeignKeyのメモ
GenericForeignKeyを調べる機会があったので重要そうなところをメモしておく。なおGenericForeignKeyはwebアプリケーションのデータ分析に役立つかもしれないと調べているが、その可否についても分かり次第記載したい。
参考url
https://docs.djangoproject.com/ja/2.1/ref/contrib/contenttypes/#generic-relations
Djangoで、GenericForeignKeyを使う
メモ
なんとなくforeignkeyと同じような機能をもちつつ、一つのモデルしかつながっていないForeignKeyをいろいろなモデルに繋げられるようにしたのがGenericForeignKeyだと思われる。こいつはmodels.pyでテーブルを作成するときに使われる。以下のようにしてモジュールを引っ張ってくる。
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType
models.pyでの書き方
Class Hoge(models.Model): ... content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericforeignKey("content_type", "object_id")
ここで注意したいことは今までフィールド定義はmodels.のあとにCharfield,IntegerFieldやForeignKeyなど書いてきた。GenericForeignKeyにおいてはmodels.の記述無しで書くこと。これはimportでGenericForeignKeyを引っ張ってきているから当たり前なのだけれどもいつもの流れで書こうとすると間違ってしまうので注意。
また3行で1セット のようだ。content_type:モデルの種類、object_id:データの主キー、content_object:左記2つを統合する。
There are three parts to setting up a GenericForeignKey: 1. Give your model a ForeignKey to ContentType. The usual name for this field is "content_type". 2. Give your model a field that can store primary key values from the models you'll be relating to. For most models, this means a PositiveIntegerField. The usual name for this field is "object_id". 3. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named "content_type" and "object_id", you can omit this -- those are the default field names GenericForeignKey will look for.
1ではforeignKey()にContentTypeを渡す。で普通はそれをcontent_typeと呼ぶ。
content_type = models.ForeignKey(ContentType)
2では関連付けたいと考えているモデルから得られるプライマリキー(主キー)の値を保存するフィールドを設定する。ほとんどのモデルでは主キーの値はPositiveIntegerFieldを意味する。そして普通はそれをobject_idと呼ぶ。
object_id = models.PositiveIntegerField()