【问题标题】:django rest framework and model inheritancedjango rest框架和模型继承
【发布时间】:2014-03-26 08:13:24
【问题描述】:

我有一个“抽象”模型类 MyField:

class MyField(models.Model):
    name = models.CharField(db_index = True, max_length=100)
    user = models.ForeignKey("AppUser", null=False)

我还有几个 MyField 的其他子类,每个子类都定义了一个特定类型的值。 例如:

class MyBooleanField(MyField):
    value = models.BooleanField(db_index = True, default=False)

在 MyField 中,我有一个 get_value() 方法,它根据特定的子类返回值。

在 django rest 中我想获取用户的所有字段

class AppUserSerializer(serializers.ModelSerializer):
    appuserfield_set = MyFieldSerializer(many=True)
    class Meta:
        model = AppUser
        fields = ('appuser_id', 'appuserfield_set')    

在客户端,我希望用户能够添加新字段并为其设置值,然后在服务器上,我希望能够根据值创建正确的字段。

实现此行为的正确方法是什么?

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    经过一番挖掘,这就是我最终要做的。除了下面的代码,我必须实现 get_or_create 并根据传递的值创建 MyField 的相关子类。

    class ValueField(serializers.WritableField):
      #called when serializing a field to a string. (for example when calling seralizer.data)
      def to_native(self, obj):
        return obj;
    
      """
      Called when deserializing a field from a string
      (for example when calling is_valid which calles restore_object)
      """
      def from_native(self, data):
        return data
    
    
    class MyFieldSerializer(serializers.ModelSerializer):
      value = ValueField(source='get_value', required=False)    
    
      def restore_object(self, attrs, instance=None):
        """
        Called by is_valid (before calling save)
        Create or update a new instance, given a dictionary
        of deserialized field values.
    
        Note that if we don't define this method, then deserializing
        data will simply return a dictionary of items.
        """
        if instance:
            # Update existing instance
            instance.user = attrs.get('user', instance.user)
            instance.name = attrs.get('name', instance.name)
        else:
            # Create new instance
            instance = MyField.get_or_create(end_user=attrs['user'],
                                                name=attrs['name'],
                                                value=attrs['get_value'])[0]
    
        instance.value = attrs['get_value']
        return instance
    
      def save_object(self, obj, **kwargs):
        #called when saving the instance to the DB
        instance = MyField.get_or_create(end_user=obj.user,
                                                name=obj.name,
                                                value=obj.value)[0]
      class Meta:
        model = MyField
        fields = ('id', 'user', 'name', 'value')
    

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2017-03-27
      相关资源
      最近更新 更多