当前位置: 动力学知识库 > 问答 > 编程问答 >

Django m2m 'through' with a generic foreignkey

问题描述:

I have the follow code example, which is a simplified abstraction of a real world project I'm working on:

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)

This line causes an error:

feature_sets = models.ManyToManyField(FeatureSet, through='Feature')

Obviously because the 'through' model lacks a corresponding FK to each side of the m2m. What I'd like to achieve here, is that one side of the m2m relationship is generic, and, that I can specify my own intermediary join table, to do the usual adding of custom fields etc.

What are my options for accomplishing this?

Note, its currently an important requirement to include the feature_sets = models.ManyToManyField(FeatureSet, through='Feature') line in the generic model, mostly for admin UI purposes. The reason why its generic is that its not yet determined how many models this line will be placed upon.

分享给朋友:
您可能感兴趣的文章:
随机阅读: