2012-02-20 12 views
2

私はTwitterリツイートのようなアプリの機能に取り組んでいます。同じモデルのDjango関連のキー

Itemのモデルでは、別のItemを参照するreposted_fromの関連フィールドを追加したいとします。私は同じモデルであるので、私はForeignKeyを使用すると思いませんが、代わりに何を使用するのですか?

答えて

6

のようなforeign key to selfを追加するのが一般的である:

class Item(models.Model): 
    parent = models.ForeignKey('self') 

あなたのようなrelated nameを指定することがあります。

class Item(models.Model): 
    parent = models.ForeignKey('self', related_name='children') 

項目が親を持っていない可能性がありますので、ヌルを忘れないでください=真で空白=真の場合:

class Item(models.Model): 
    parent = models.ForeignKey('self', related_name='children', null=True, blank=True) 

次に、以下のようなldren:

item.children 

あなたにもdjango-mpttといくつかの最適化と、余分なツリー機能の利点を使用する場合があります。

from mptt.models import MPTTModel, TreeForeignKey 

class Item(MPTTModel): 
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children') 
-1

文字列を使用する場合に限り、同じモデルでforegeinキーを使用します。

class Item(models.Model): 
    foo = models.ForeignKey("reposted_from") 

class reposted_from(models.Model): 
    repost_from = models.CharField(max_length=122) 

などです。

それ以外の場合は、未定義の参照を取得します。 それはあなたが必要なものですか?

+0

私は作品とは思いません。 FKコンストラクタのシグネチャは、ForeignKey(othermodel [、** options])クラスです。したがって、 "reposted_from"が別のモデルの名前でない限り、これは動作しませんhttps://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey – jpic

関連する問題