简体   繁体   中英

Django rest framework, difficulty understanding foreign Key field serialization

I'm trying to learn the relations in the Django rest framework and the serializer's job in then.

I have the following model:

from django.db import models


class Point(models.Model):
    Latitude = models.FloatField(verbose_name="Latitude",
                                 blank=False)
    Longitude = models.FloatField(verbose_name="Longitude",
                                  blank=False)
    elevation = models.FloatField(verbose_name='Location Elevation',
                                  blank=False,
                                  default=1)


class Location(models.Model):
    location_name = models.TextField(unique=True, blank=False, verbose_name="Location Name")
    location_coordinates = models.ForeignKey(Point,
                                             on_delete=models.CASCADE,
                                             verbose_name='Latitude & Longitude')

    class Meta:
        unique_together = ['location_name', 'location_coordinates']
        get_latest_by = 'date_added'

    def __str__(self):
        return f'{self.location_name},{self.location_coordinates}'

And, this serializer:

from rest_framework import serializers

from .models import Location


class LocationSerializer(serializers.ModelSerializer):
    location_name = serializers.RelatedField(many=True, read_only=True)

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        print(representation)
        return representation

    class Meta:
        model = Location
        fields = ['location_name']

Now, I'm trying to access the serialized data, so I can run my logic on it and return the response in the view.

The framework's docs kind of jump into deep water in this topic (at least for me)

So, I have two questions:

  1. How do I access the serialized data In the serializer?
  2. Where can I run my business logic on it, which returns a folium rendered HTML File, I prefer to do it in the serializer and not in the view, so It can be returned upon the post request and not in some kind of retrieve method, Which means creating a new field in the serializer that can be returned to the user.

Edit:

I changed my serializer to so:

class PointSerializer(serializers.ModelSerializer):
    class Meta:
        model = Point
        field = '__all__'


class LocationSerializer(serializers.ModelSerializer):
    # mission_file = serializers.PrimaryKeyRelatedField(many=True,read_only=True)

    class Meta:
        model = Location
        fields = ['location_name', 'location_coordinates']

The access data is as follows:

In [4]: queryset = Location.objects.all()

In [5]: data = queryset[2]

In [6]: location = LocationSerializer(data)

In [7]: location_data_f = location.data.items()

In [8]: print(location_data_f)
odict_items([('location_name', 'created'), ('location_coordinates', 3)])

In [9]: data = queryset[3]

In [10]: location = LocationSerializer(data)

In [11]: location_data_f = location.data.items()

In [12]: print(location_data_f)
odict_items([('location_name', 'newday'), ('location_coordinates', 4)])

How do I access the data on location_coordinates, not it's id.

You can just use serializer.data to get serialized json:

>>> serialized_data = LocationSerializer(data,many=False)
>>> print(serialized_data)
LocationSerializer(<Location: yovel,Point object (1)>):
>>> serailizer.data

To perform logic on serializer level you can use SerializerMethodfield .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM