我有以下代码示例,它是我正在处理的真实世界项目的简化抽象:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class FeatureSet(models.Model):
"""
Feature Set
"""
name = models.CharField(max_length=255)
def __unicode__(self):
return u"%s" % self.name
class GenericObjectAlpha(models.Model):
title = models.CharField(max_length=255)
feature_sets = models.ManyToManyField(FeatureSet, through='Feature')
def __unicode__(self):
return u"%s" % self.title
class GenericObjectBeta(models.Model):
title = models.CharField(max_length=255)
feature_sets = models.ManyToManyField(FeatureSet, through='Feature')
def __unicode__(self):
return u"%s" % self.title
class Feature(models.Model):
"""
Feature
"""
# FK to feature set
feature_set = models.ForeignKey(FeatureSet)
# FK to generic object, Generic object alpha or beta... or others
content_type = models.ForeignKey(
ContentType,
default='article',
limit_choices_to={ 'model__in': ('genericobjectalpha', 'genericobjectbeta') },
related_name="play__feature_set__feature")
object_id = models.PositiveIntegerField(
"Feature object lookup")
content_object = generic.GenericForeignKey(
'content_type',
'object_id')
# Extra fields on a m2m relationship
active = models.BooleanField()
order = models.PositiveIntegerField()
def __unicode__(self):
return u"%s::%s" % (self.feature_set, self.content_object)
此行会导致错误:
feature_sets = models.ManyToManyField(FeatureSet, through='Feature')
显然因为'通过'模型在m2m的每一侧缺少相应的FK。我想在这里实现的是,m2m关系的一方是通用的,并且我可以指定我自己的中间连接表,通常添加自定义字段等。
我有什么选择来实现这个目标?
注意,它目前是在通用模型中包含feature_sets = models.ManyToManyField(FeatureSet, through='Feature')
行的一个重要要求,主要用于管理UI用途。其通用性的原因在于它还没有确定这条线将被放置多少型号。