我尝试访问manytomy链接的through表上的字段,通过Django Rest框架将其序列化为JSON。在
我参与多对多的模型有:
class Mage(models.Model):
arcana = models.ManyToManyField('ArcanumAbility', through='CharacterArcanumLink', related_name='mage_by_arcana')
class ArcanumAbility(models.Model):
class Arcana(AutoNumber):
FATE = ()
MIND = ()
SPIRIT = ()
DEATH = ()
FORCES = ()
TIME = ()
SPACE = ()
LIFE = ()
MATTER = ()
PRIME = ()
arcanum = EnumField(Arcana)
class Meta:
verbose_name_plural = "Arcana Abilities"
def __str__(self):
return self.arcanum.label
class CharacterArcanumLink(Trait):
PRIORITY_CHOICES = (
(0, 'Unassigned'), (1, 'Ruling'), (2, 'Common'), (3, 'Inferior')
)
priority = models.PositiveSmallIntegerField(
choices=PRIORITY_CHOICES, default=0)
mage = models.ForeignKey('Mage')
arcana = models.ForeignKey('ArcanumAbility')
class Meta:
unique_together = ('mage', 'arcana')
def __str__(self):
return self.arcana.arcanum.label
其中Trait
mixin提供了一个current_value
为了将上述关系序列化为JSON,我在序列化程序上尝试了以下两种模式:
^{pr2}$但这给了我一个错误:
AttributeError at /mages
'ManyRelatedManager' object has no attribute 'arcana'
它来自(最终):
C:\Python34\lib\site-packages\rest_framework\fields.py in get_attribute
if instance is None:
# Break out early if we get `None` at any point in a nested lookup.
return None
try:
if isinstance(instance, collections.Mapping):
instance = instance[attr]
else:
instance = getattr(instance, attr) ...
except ObjectDoesNotExist:
return None
if is_simple_callable(instance):
instance = instance()
return instance
▼ Local vars
Variable: Value
instance: <django.db.models.fields.related.create_many_related_manager.<locals>.ManyRelatedManager object at 0x0000000004E4D4A8>
attr: 'arcana'
attrs: ['arcana']
(问题:我需要什么技巧才能从我的多个相关经理转到it领域?)在
我还尝试不指定特殊的序列化程序,只在字段中使用'arcana'
,然后从模型中提取它。这导致了这个错误:
TypeError at /mages
<Arcana.FATE: 1> is not JSON serializable
其中1
来自于神秘性的PK,而不是through表上的值。这里的问题是Mage类有一个指向'ArcanumAbility'
模型的M2M字段,因此DRF所要做的就是序列化它上的枚举。在
那么,如果我想要一个JSON字典,其中包含从Mage到archablability的所有关系,以及through表中的数据,我应该使用什么方法呢?在
对于Mark R.,我希望它看起来像这样:
....
"arcanum": {
"Fate": 2,
"Spirit": 0,
"Mind": 3,
....
}
希望这是一个足够清晰的样本。在
我这样做了:
深受this答案的启发。在
如前所述,如果在CharacterArcanumLink类的mage字段中添加一个相关的_name=“linked_arcana”,您应该能够执行以下操作:
相关问题 更多 >
编程相关推荐