简体   繁体   中英

How to solve in Django REST API the serializing of data from 2 models with ForeignKey

I was wondering what the correct way is to serialize data in Django REST API from 2 models connected with ForeignKey.
The situation is: i have a 1st table called NewUsers with the user registrations, and a 2nd table called Ticker with data saved from an external API.
The goal is: create a 3rd table with parts of the 2 tables interconnected - one part is the user loggedin, and the other part is the selection of one crypto object. This new table will then be displayed via Django REST API serializer.
The problem is: this new 3rd table does not display the complete list of values selected by the user.
I have gone through the documentation here https://books.agiliq.com/projects/django-admin-cookbook/en/latest/override_save.html and herehttps://www.django-rest-framework.org/tutorial/1-serialization/ but could not find a complete solution. What am i missing?

views.py:

from rest_framework import generics
from .serializers import WatchlistSerializer
from ticker.serializers import TickerSerializer
from watchlist.models import SectionWatchlist
from ticker.models import Ticker
import requests
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
     
class CreateSectionWatchlist(generics.CreateAPIView):
    queryset = SectionWatchlist.objects.all()
    serializer_class = WatchlistSerializer

class ListSectionWatchlist(generics.ListAPIView):
    queryset = SectionWatchlist.objects.all()
    serializer_class = WatchlistSerializer
    
    def get_queryset(self):
        queryset = SectionWatchlist.objects.all()
        author = self.request.query_params.get('author')
        if author:
            queryset = queryset.filter(author=author)
        return queryset
    
class DeleteSectionWatchlist(generics.RetrieveDestroyAPIView):
    queryset = SectionWatchlist.objects.all()
    serializer_class = WatchlistSerializer

models.py:

from django.db import models
from django.conf import settings
from ticker.models import Ticker
    
class SectionWatchlist(models.Model):
    id = models.AutoField(primary_key=True)  # auto increment field
    tickerlist = models.ForeignKey(Ticker, related_name="tickerinfo", on_delete=models.CASCADE)
    crypto = models.CharField(blank=True, null=True, max_length=40)
    c_0 = models.FloatField(null=True, blank=True, default=None)
    o_0 = models.FloatField(null=True, blank=True, default=None)
    percentage = models.FloatField(null=True, blank=True, default=None)
    user_name = models.CharField(blank=True, null=True, max_length=40)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, blank=True, null=True,
        on_delete=models.CASCADE,
    )

serializers.py:

from rest_framework import serializers
from watchlist.models import SectionWatchlist
from ticker.models import Ticker
from ticker.serializers import TickerSerializer

class WatchlistSerializer(serializers.ModelSerializer):
    crypto = TickerSerializer()
    class Meta:
        model = SectionWatchlist
        fields = ('id','tickerlist','author', 'crypto')

the Django REST API incomplete response

{
        "id": 88,
        "tickerlist": 36,
        "author": 6,
        "crypto": {
            "crypto": null,
            "c_0": null,
            "o_0": null
        }
    }
]

admin.py:

from django.contrib import admin
from django import forms
from . import models
from ticker.models import Ticker

@admin.register(models.SectionWatchlist) 
class WatchlistAdmin(admin.ModelAdmin):
    list_display = (
                    'id', 
                    # 'percentage',
                    'tickerlist',
                    # 'user_name',
                    'author',
                    'get_crypto',
                    'get_c_0',
                    'get_o_0',
    )
    
    
    @admin.display(ordering='watchlist__tickerlist', description='get_crypto')
    def get_crypto(self, obj):
        return obj.tickerlist.crypto
    
    @admin.display(ordering='watchlist__tickerlist', description='c_0')
    def get_c_0(self, obj):
        return obj.tickerlist.c_0
    
    @admin.display(ordering='watchlist__tickerlist', description='o_0')
    def get_o_0(self, obj):
        return obj.tickerlist.o_0
    

Actually my admin displays the response correctly with complete values: 在此处输入图像描述 .

How can I have the serialized response in Django REST API complete?

I think you need to set the serializer for the foreign key fields.

class WatchlistSerializer(serializers.ModelSerializer):
    tickerlist= TickerSerializer()
    author = UserSerializer()

    class Meta:
        model = SectionWatchlist
        fields = ('id', 'tickerlist', 'author', 'crypto')

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