首页 文章

Django-Rest-Framework序列化器类元

提问于
浏览
6

因为我可以在元模型类中使用两个,当我运行它时,我得到一个错误如何使用模型?这是Django Rest的一个例子

from rest_framework import serializers
from .models import Post,Miembros

class PostSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'url', 'titulo', 'contenido','fecha_evento','fecha_evento','banner_grande','lugar')

        model = Miembros
        fields = '__all__'

/ api / posts /中的TypeError字段选项必须是列表或元组 . 得了str . 请求方法:GET请求URL:http://127.0.0.1:8000 / api / postts / Django版本:1.8.3异常类型:TypeError异常值:fields选项必须是列表或元组 . 得了str . 异常位置:/home/root-master/restcosolg/cslg/local/lib/python2.7/site-packages/rest_framework/serializers.py in get_field_names,第900行Python可执行文件:/ home / root-master / restcosolg / cslg / bin / python Python版本:2.7.6

1 回答

  • 9

    Update (5 May 2016):

    all value for fields is now supported in ModelSerializer(Thanks @wim for pointing out).

    您还可以将fields属性设置为特殊值'all',以指示应使用模型中的所有字段 . 如果您只想在模型序列化程序中使用默认字段的子集,则可以使用字段或排除选项,就像使用ModelForm一样 . 强烈建议您使用fields属性显式设置应序列化的所有字段 . 这样可以减少模型更改时无意中暴露数据的可能性 .

    您似乎正在尝试将Django ModelForm fields属性与DRF序列化程序字段属性混合使用 . 在DRF序列化程序中,__ all__是fields属性的无效值 .

    Secondly, 您无法在 Meta 类中指定多个模型 . 您将需要使用2个单独的序列化程序并将它们相互连接 .

    例如,您可以执行以下操作:

    from rest_framework import serializers
    from .models import Post,Miembros
    
    
    class MiembrosSerializer(serializers.ModelSerializer):
        """
        serializer for Miembros model
        """
    
        class Meta:
            model = Miembros 
            fields = '__all__' # all model fields will be included
    
    
    class PostSerializer(serializers.HyperlinkedModelSerializer):
        """
        serializer for Post model
        """
    
        miembros = MiembrosSerializer()
    
        class Meta:
            model = Post
            fields = ('id', 'url', 'titulo', 'contenido','fecha_evento','fecha_evento','banner_grande','lugar')
    

相关问题