混合Django Rest Framework中序列化器之间的公共字段

时间:2015-02-26 16:21:08

标签: python django django-rest-framework mixins

我有这个:

class GenericCharacterFieldMixin():
    attributes = serializers.SerializerMethodField('character_attribute')
    skills = serializers.SerializerMethodField('character_skill')

    def character_attribute(self, obj):
        character_attribute_fields = {}
        character_attribute_fields['mental'] = {str(trait_item.get()): trait_item.get().current_value
                                                for trait_item in obj.mental_attributes}
        character_attribute_fields['physical'] = {str(trait_item.get()): trait_item.get().current_value
                                                  for trait_item in obj.physical_attributes}
        character_attribute_fields['social'] = {str(trait_item.get()): trait_item.get().current_value
                                                for trait_item in obj.social_attributes}
        return character_attribute_fields

    def character_skill(self, obj):
        character_skill_fields = {}
        character_skill_fields['mental'] = {str(trait_item.get()): trait_item.get().current_value
                                            for trait_item in obj.mental_skills}
        character_skill_fields['physical'] = {str(trait_item.get()): trait_item.get().current_value
                                              for trait_item in obj.physical_skills}
        character_skill_fields['social'] = {str(trait_item.get()): trait_item.get().current_value
                                            for trait_item in obj.social_skills}
        return character_skill_fields


class MageSerializer(GenericCharacterFieldMixin, serializers.ModelSerializer):
    player = serializers.ReadOnlyField(source='player.username')
    arcana = serializers.SerializerMethodField()

    def get_arcana(self, obj):
        if obj:
            return {str(arcana): arcana.current_value for arcana in obj.linked_arcana.all()}

    class Meta:
        model = Mage
        fields = ('id', 'player', 'name', 'sub_race', 'faction', 'is_published',
                  'power_level', 'energy_trait', 'virtue', 'vice', 'morality', 'size',
                  'arcana', 'attributes', 'skills')
        depth = 1

GenericCharacterFieldMixin是字符字段的混合,是通用的,即对所有类型的字符都是通用的。

我希望我的Mage Serializer能够将这些'混合在一起。而不是c / p然后在所有类型的角色之间(法师是一种角色)希望这会增加我的webapp中的干燥。

问题在于我的模型:

class NWODCharacter(models.Model):

    class Meta:
        abstract = True
        ordering = ['updated_date', 'created_date']

    name = models.CharField(max_length=200)
    player = models.ForeignKey('auth.User', related_name="%(class)s_by_user")
    ....

    def save(self, *args, **kwargs):
        ...

    attributes = GenericRelation('CharacterAttributeLink')
    skills = GenericRelation('CharacterSkillLink')

这意味着我收到此错误:

TypeError at /characters/api/mages
<django.contrib.contenttypes.fields.create_generic_related_manager.<locals>.GenericRelatedObjectManager object at 0x00000000051CBD30> is not JSON serializable

Django Rest Framework认为我想序列化我的通用关系。

如果我重命名模型中的字段(s/attributes/foos/gs/skills/bars/g),那么我会得到一个不同的(不太清楚?)错误:

ImproperlyConfigured at /characters/api/mages
Field name `attributes` is not valid for model `ModelBase`.

如何将这些方法和字段放入mixin中,而不会混淆DRF?

3 个答案:

答案 0 :(得分:15)

解决方案很简单,如改变

class GenericCharacterFieldMixin():

class GenericCharacterFieldMixin(serializers.Serializer):

答案 1 :(得分:3)

我有同样的问题,我的谷歌搜索把我带到了这里。我设法解决了它。  由于您在序列化程序中包含属性和技能字段,因此需要为其提供序列化方法。

这对我有用

SELECT * from
(
SELECT 1 
UNION ALL 
SELECT 2 
) a
ORDER by ...

答案 2 :(得分:3)

设置SerializerMetaclass

from rest_framework import serializers

class GenericCharacterFieldMixin(metaclass=serializers.SerializerMetaclass):
    # ...

这是解决方案recommended by DRF's authors

先前答案中提出的解决方案存在问题:

  1. user1376455的解决方案通过将子对象上的mixin字段声明为不同的字段,从而使DRF在_declared_fields中注册了mixin的字段。此hack可能在框架的后续版本中不起作用。
  2. Nikolay Fominyh的解决方案将mixin更改为完整的序列化器(请注意,由于这个原因,GenericCharacterFieldMixin对于不是mixin而是序列化器的类非常不幸!)。这是有问题的,因为它将完整的Serializer类带入了多重继承,请参见DRF issue的示例来说明为什么这是一个坏主意。