Django Rest Framework: get all data in relation

2019-07-24 13:37发布

问题:

So, I have a Django Application and I try to get all information in JSON format or QuerySet format:

models.py

class Flow(models.Model):
    name = models.CharField("nom", primary_key=True, max_length=255)
    BL_applicative = models.CharField("BL applicative", max_length=255,blank=True, null=True)
    comment = models.TextField("commentaire", max_length=1500,blank=True,null=True)
    application = models.ForeignKey('Application', null=True)

class Development(models.Model):
    stability = models.IntegerField("stabilité", default=0)
    unit_test = models.IntegerField("tests unitaires", default=0)
    documentation = models.IntegerField(default=0)
    conception = models.IntegerField(default=0)
    production = models.IntegerField("réalisation", default=0)
    flow = models.ForeignKey('Flow',blank=True,null=True)

class Segment(models.Model):
    index_number = models.IntegerField("indice")
    chain_batch_fueled = models.CharField(max_length=255, blank=True,null=True)
    comment = models.TextField("commentaire", max_length=1500, blank=True,null=True)
    development = models.ForeignKey('Development',verbose_name="Développement", blank=True,null=True)

In a standalone script I want to get all data, so I used:

seg_ser = serializers.serialize('json', Segment.objects.all())

And this is the result:

[
  {
    "model": "dashboard_tibco.segment",
    "pk": 3,
    "fields": {
      "index_number": 1,
      "chain_batch_fueled": "",
      "comment": "",
      "development": 10
   }
  },
]

As you can see, only informations of data are here, but not the informations of development, flow and application...

Any solution to get all fields of development object and the same for flow object and application object?

Solution: Thanks Jamie for your help!

So, this is my serializers.py:

from rest_framework import serializers

from dashboard_tibco.models import Development, Segment


class DevelopmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Development
        fields = '__all__'


class SegmentSerializer(serializers.ModelSerializer):
    development = DevelopmentSerializer(read_only=True)

    class Meta:
        many = True
        model = Segment
        fields = '__all__'

My view.py:

from django.http import HttpResponse
from dashboard_tibco.transformation_document.document import Document
def get_json_doc(request):
    return HttpResponse(Document().get_sql_data_by_application('GRS'))

My urls.py:

from django.conf.urls import url
from django.contrib import admin


from dashboard_tibco.views import get_json_doc

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^json', get_json_doc, name='json'),
]

My standalone script with django rest serializers:

class Document(object):
    def __init__(self):
        /..Make something../

    def get_sql_data_by_application(self):
        serializer = SegmentSerializer(Segment.objects.all(), many=True)
        return JSONRenderer().render(serializer.data)

And the result of JSONRenderer:

[
  {
    "id": 3,
    "development": {
        "id": 10,
        "status": "En cours",
        "stability": 0,
        "unit_test": 0,
        "documentation": 0,
        "conception": 0,
        "production": 0,
        "modification_date": null,
        "flow": "Batch",
        "achievement_lot": null,
        "project": null
     },
     "name": "",
     "index_number": 1,
     "pivot_subscribed": "",
     "pivot_published": "",
     "chain_batch_fueled": "",
     "comment": "",
     "called": null,
     "caller": null,
     "tuxedo_adapter": null
  },
]

回答1:

I'm going to assume you're using the Django Rest Framework.

You need to create a custom serializer. I have not tested it, but it would be something like this:

class DevelopmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Development

class SegmentSerializer(serializers.ModelSerializer):
    development = DevelopmentSerializer(read_only=True)
    class Meta:
        many = True
        model = Segment

This tells the SegementSerializer to use the DevelopmentSerializer when serializing the development data. By default it uses a PrimaryKeyRelatedField which is why you just see the ID (in this case, 10).