如何从Django REST访问完整对象JSON图?

时间:2018-04-26 13:40:42

标签: django hibernate django-models orm django-rest-framework

我有Django模型,序列化器和视图:

from django.db import models

# Create your models here.
class Contract(models.Model):
    contract_no = models.IntegerField(blank=False, unique=True)
    customer = models.IntegerField(blank=False)
    agent = models.IntegerField(blank=False)
    agency = models.IntegerField(blank=False)
    cont_date = models.DateField()

    def __str__(self):
        """Return a human readable representation of the model instance."""
        return "{}".format(self.contract_no)

class ContractOrder(models.Model):
    order_no = models.IntegerField(blank=False, unique=True)
    order_date = models.DateField()
    contract = models.ForeignKey(Contract, on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.order_no

    class Meta:
        ordering = ('order_no',)


from rest_framework import serializers
from .models import Contract
from .models import ContractOrder

class ContractSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Contract
        fields = ('contract_no', 'customer', 'agent', 'agency', 'cont_date')
        #read_only_fields = ('date_created', 'date_modified')

class ContractOrderSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = ContractOrder
        fields = ('order_no', 'order_date', 'contract')
        #read_only_fields = ('date_created', 'date_modified')


from rest_framework import generics
from .serializers import ContractSerializer
from .models import Contract
from .serializers import ContractOrderSerializer
from .models import ContractOrder

class ContractCreateView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    queryset = Contract.objects.all()
    serializer_class = ContractSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new bucketlist."""
        serializer.save()

class ContractOrderCreateView(generics.ListCreateAPIView):
    """This class defines the create behavior of our rest api."""
    queryset = ContractOrder.objects.all()
    serializer_class = ContractOrderSerializer

    def perform_create(self, serializer):
        """Save the post data when creating a new bucketlist."""
        serializer.save()

结果/合同和/ contract_orders JSON消息很简单:

[{"contract_no":1,"customer":1,"agent":1,"agency":1,"cont_date":"2018-04-26"},{"contract_no":2,"customer":2,"agent":2,"agency":2,"cont_date":"2018-04-25"}]

[{"order_no":1,"order_date":"2018-04-26","contract":1}]

但我希望有更多扩展的JSON消息,特别是:

  1. 合同JSON实体应该有ContractOrder实体数组(在我的情况下,合同1应该有1个条目的数组)

  2. ContractOrder JSON实体应该具有扩展的合同实体 - 目前合同字段(在JSON中)仅包含标量值1,但我希望拥有完整的合同实体。

  3. 当然 - 有些情况下JSON图应该完全展开,何时应该收缩,然后会出现扩展应该是部分的情况?是否有可能在Django中实现这一目标?

    我有经验,在Java JPA / Hibernate / Spring中,可以使用注释@OneToMany@JsonView来控制实体图(在内存中)和实体图的JSON视图(在REST中) (来自com.fasterxml.jackson.annotation.JsonView库)但是如何在Django中实现这一点 - 两者 - 在内存和REST JSON消息中?

1 个答案:

答案 0 :(得分:3)

按如下方式更改序列化程序:

class SimpleContractOrderSerializer(serializers.ModelSerialiser):  # Required; otherwise you get into a recursive loop.
    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = ContractOrder
        fields = ('order_no', 'order_date',)

class ContractSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""
    contract_order = SimpleContractOrderSerializer(source='contractorder', many=True, read_only=True)

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = Contract
        fields = ('contract_no', 'customer', 'agent', 'agency', 'cont_date')
        #read_only_fields = ('date_created', 'date_modified')

class ContractOrderSerializer(serializers.ModelSerializer):
    """Serializer to map the Model instance into JSON format."""
    contract = ContractSerializer(read_only=True)

    class Meta:
        """Meta class to map serializer's fields with the model fields."""
        model = ContractOrder
        fields = ('order_no', 'order_date', 'contract')
        #read_only_fields = ('date_created', 'date_modified')

在此处阅读更多内容:http://www.django-rest-framework.org/api-guide/relations/#nested-relationships