「auth.Group」とその他のカスタム モデルの間に中間モデル、Permissions を作成しようとしています。これは、許可またはどのグループに何が表示されるかの手段として機能します。
「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))
ただし、問題は、これが再利用性に反することです。カスタム モデルを関連付けることができるモデルを作成するために、次のように、ForeignKey の代わりに GenericForeignKey を実装しました。
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: (fields.E336) モデルは 'simulations.Dumby.groups' によって中間モデルとして使用されますが、'Dumby' または ' への外部キーがありません。グループ'。
一見すると、中間テーブルで GenericForeignKey を使用することは行き止まりのように見えます。この場合、カスタム モデルごとにカスタム中間モデルを作成するという面倒で冗長なアプローチ以外に、そのような状況を処理する一般的に受け入れられている方法はありますか?