从其他模型访问对象-Django

时间:2020-08-03 13:56:35

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

嗨,我有以下两种型号

class IndexMaster(models.Model):
    index_id = models.IntegerField(primary_key=True)
    index_name = models.CharField(max_length=100)
    index_on = models.CharField(max_length=10)
    index_type = models.CharField(max_length=20)

    def __str__(self):
        return self.index_id

class Meta:
    managed = True
    db_table = 'index_master'

class IndexData(models.Model):
    index = models.ForeignKey(IndexMaster, on_delete=models.CASCADE)
    lifetime_high = models.FloatField()
    lifetime_low = models.FloatField()
    yearly_high = models.FloatField()
    yearly_low = models.FloatField()
    yesterdays_close = models.FloatField()
    day_high = models.FloatField()
    day_low = models.FloatField()
    todays_open = models.FloatField()
    lastvalue = models.FloatField()
    change = models.FloatField()
    percentchange = models.FloatField()


    class Meta:
        managed = True
        db_table = 'index_data'

我的serialiser.py看起来像这样

from rest_framework import serializers

from .models import IndexData

class IndexSerializer(serializers.ModelSerializer):

    class Meta:

        model = IndexData
        fields = ['index' ,'day_high', 'day_low', 'lastvalue', 'change', 'percentchange']

    def to_representation(self, instance):
        ret = super(IndexSerializer, self).to_representation(instance)

        return ret

and views.py就像

class IndexList(generics.ListAPIView):
    queryset = IndexData.objects.all()

    serializer_class = IndexSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        query_params = self.request.query_params
        indexID = query_params.get('index_id', None)

        Q1 = Q(index_id = indexID)

        return IndexData.objects.filter(Q1)

问题是当我点击url以获取JSON时,我得到以下响应

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "index": 3.0,
            "day_high": 8867.2,
            "day_low": 8725.25,
            "lastvalue": 8746.85,
            "change": -97.95,
            "percentchange": -1.1
        }
    ]
}

我想要包含IndexMaster模型中的index_name,index_on和index_type。 我该如何实现? 我想要的JSON响应是

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "index": 3.0,
            "index_name": "XXXX",
            "index_on": "XXXX",
            "index_type": "XXXX",
            "day_high": 8867.2,
            "day_low": 8725.25,
            "lastvalue": 8746.85,
            "change": -97.95,
            "percentchange": -1.1
        }
    ]
}

XXXX替换为IndexMaster的实际值

2 个答案:

答案 0 :(得分:0)

您可以像这样创建关系模型的序列化器:

class IndexMasterSerializer(serializers.ModelSerializer):
      class Meta:
            model = IndexMaster
            fields = '__all__'

class IndexSerializer(serializers.ModelSerializer):
      index = IndexMasterSerializer() # you indicat the field "index" need to be serializer by IndexMasterSerializer
    class Meta:
        model = IndexData
        fields = ['index' ,'day_high', 'day_low', 'lastvalue', 'change', 'percentchange']

结果如下:

"results": [
    {
        "index": {
            "index_id": "XXXXX",
            "index_name": "XXXX",
            "index_on": "XXXX",
            "index_type": "XXXX"
        },
        "day_high": 8867.2,
        "day_low": 8725.25,
        "lastvalue": 8746.85,
        "change": -97.95,
        "percentchange": -1.1
    }
  ]

答案 1 :(得分:0)

您可以这样添加它们(使用source):

{
  "architectures": [
    "CamembertForMultiLabelSequenceClassification"
  ],
  "attention_probs_dropout_prob": 0.1,
  "bos_token_id": 5,
  "eos_token_id": 6,
  "gradient_checkpointing": false,
  "hidden_act": "gelu",
  "hidden_dropout_prob": 0.1,
  "hidden_size": 768,
  "id2label": {
    "0": "LABEL_0",
    "1": "LABEL_1",
    "2": "LABEL_2",
    "3": "LABEL_3",
    "4": "LABEL_4",
    "5": "LABEL_5",
    "6": "LABEL_6",
    "7": "LABEL_7",
    "8": "LABEL_8",
    "9": "LABEL_9"
  },
  "initializer_range": 0.02,
  "intermediate_size": 3072,
  "label2id": {
    "LABEL_0": 0,
    "LABEL_1": 1,
    "LABEL_2": 2,
    "LABEL_3": 3,
    "LABEL_4": 4,
    "LABEL_5": 5,
    "LABEL_6": 6,
    "LABEL_7": 7,
    "LABEL_8": 8,
    "LABEL_9": 9
  },
  "layer_norm_eps": 1e-05,
  "max_position_embeddings": 514,
  "model_type": "camembert",
  "num_attention_heads": 12,
  "num_hidden_layers": 12,
  "output_past": true,
  "pad_token_id": 1,
  "type_vocab_size": 1,
  "vocab_size": 32005
}