2016-09-28 19 views
0

'auth.Group'と他のカスタムモデルとの間にPermissionsという中間モデルを作成しようとしています。これは、アクセス許可またはどのグループに表示されるかの手段として機能します。中間モデルのGenericForeignKeys

「auth.Group」と1つのモデルの間に、中間モデルのExamplePermissionsを作成することができました。

class Example(TimeStampable, Ownable, Model): 
     groups = models.ManyToManyField('auth.Group', through='ExamplePermissions', related_name='examples') 
     name = models.CharField(max_length=255) 
     ... 
     # Used for chaining/mixins 
     objects = ExampleQuerySet.as_manager() 

     def __str__(self): 
      return self.name 

    class ExamplePermissions(Model): 
     example = models.ForeignKey(Example, related_name='group_details') 
     group = models.ForeignKey('auth.Group', related_name='example_details') 
     write_access = models.BooleanField(default=False) 

     def __str__(self): 
      return ("{0}'s Example {1}").format(str(self.group), str(self.example)) 

ただし、これは再利用に反対するという問題があります。

class Dumby(Model): 
     groups = models.ManyToManyField('auth.Group', through='core.Permissions', related_name='dumbies') 
     name = models.CharField(max_length=255) 

     def __str__(self): 
      return self.name 

    class Permissions(Model): 
     # Used to generically relate a model with the group model 
     content_type = models.ForeignKey(ContentType, related_name='group_details') 
     object_id = models.PositiveIntegerField() 
     content_object = GenericForeignKey('content_type', 'object_id') 
     # 
     group = models.ForeignKey('auth.Group', related_name='content_details') 
     write_access = models.BooleanField(default=False) 

     def __str__(self): 
      return ("{0}'s Content {1}".format(str(self.group), str(self.content_object))) 

をして移行、それ誤りを作るしようとしたら:
core.Permissions:任意のカスタムモデルは、それに関連付けられていることを可能にするモデルを作成するために、私は次のようにのForeignKeyの代わりにGenericForeignKeyを実装しました(fields.E336)モデルは 'simby.Dumby.groups'によって中間モデルとして使用されますが、 'Dumby'または 'Group'への外部キーはありません。

一見、中間テーブルでGenericForeignKeyを使用すると、デッドエンドのように見えます。この場合、カスタムモデルごとにカスタム中間モデルを作成する煩雑で冗長なアプローチの他に、こうした状況を処理する一般的に認められた方法がありますか?

答えて

1

中間モデルでGenericForeignKeyを使用するときはManyToManyFieldを使用しないでください。あなたのグループのフィールドは、単にとして宣言されますので、代わりに、GenericRelationを使用します。

groups = generic.GenericRelation(Permissions) 

詳細はreverse generic relationsを参照してください。

+0

中間モデルにManyToManyFieldがありません。 Permissionsは中間モデル – QuintoViento

+0

です。私は「DumbyでManyToManyFieldを使用しないでください...」と言っていました。うまくいけば、ManyToManyFieldをGenericRelationに置き換えることです。 – blhsing

関連する問題