在json

时间:2016-08-21 00:22:28

标签: django serialization django-models django-rest-framework django-serializer

模型

class makitVerifications(models.Model):

Matter_fk = models.ForeignKey(Matter,on_delete=models.CASCADE , related_name = "makit_validate")

user_fk =  models.ForeignKey('auth.User',on_delete=models.CASCADE ,  related_name = 'verification_by'   , )

串行

class UserVerifyCountSerializer(serializers.ModelSerializer):

# Tried makit_validate = makitSerializer (read_only = True)

class Meta :

    model = makitVerifications
    fields = (  'user_fk', 'makit_validate', 'Matter_fk')

UserVerifyCountSerializer._declared_fields [' makit_validate'] = makitSerializer(read_only = True)

视图

class UserVerfiyCountViewSet(generics.ListCreateAPIView):

serializer_class = UserVerifyCountSerializer

def get_queryset(self):

    queryset = makitVerifications.objects.all()

    return queryset

JSON

{     "计算":2,     " next":null,     "之前":null,     "结果":[         {             " user_fk":1,             " Matter_fk":1         },         {             " user_fk":1,             " Matter_fk":1         }     ]

字段" makit_validate"预期JSON中缺少嵌套对象。如何在json中获取相关模型的嵌套对象。

我还尝试了文档中的示例,但JSON缺少相同的字段

此外,如何省略/禁用嵌套在上述序列化程序类

中的对象的字段

Makie Serilazer

类makitSerializer(serializers.ModelSerializer):

kamaz = kamazSerializer(many=True,read_only=True)

facilities = FacilitiesSerializer (many =True,read_only=True)

class Meta :

    model = Makit

    fields = '__all__'

## Makit Model ##
class Makit (models.Model): 
    pincode = models.IntegerField()

    area = models.CharField(max_length=200)

    street = models.CharField(max_length=200)

    landmark = models.CharField(max_length=100,blank=True , null = True)

    contact_no= models.BigIntegerField()

1 个答案:

答案 0 :(得分:1)

来自doc:Serializer fields

尝试:

makit_validate = makitSerializer(source="the_field_you_find_makit" read_only = True)