Django v1.10: получение JSON всех моделей `Country`, хранящихся в модели` Continent` - PullRequest
0 голосов
/ 14 октября 2018

У меня есть следующие модели:

from django.db import models

MNL = 50
MCL = 5


class Continent(models.Model):


    """
    Fields
    """
    name = models.CharField("name", max_length=MNL, unique=True)
    code = models.CharField("code", max_length=MCL, default="", unique=True)
    class Meta:
        ordering = ['name']

    """
    Methods
    """
    def __str__(self):
        return "%s, %s" % (self.name, self.code)


class Country(models.Model):

    """
    Fields
    """
    name = models.CharField("name", max_length=MNL, unique=True)
    capital = models.CharField("capital", max_length=MNL)
    code = models.CharField("code", max_length=MCL, default="", unique=True)
    population = models.PositiveIntegerField("population")
    area = models.PositiveIntegerField("area")
    continent = models.ForeignKey(Continent, on_delete=models.CASCADE,
        related_name="countries")
    class Meta:
        ordering = ['name']


    """
    Methods
    """
    def __str__(self):
        return "%s, %s" % (self.name, self.code)

Мне нужно иметь возможность получить 2 вещи в JSON (P):

  1. индивидуальный Country * capital, population и area поля в форме {"area":<area>,"population":<population>,"capital":<capital_name>} и
  2. в случае Continent, все страны на этом континенте в форме {"code1":"name1", "code2":"name2",...}

Я пытался реализовать следующие представления для достижения этой цели:

from django.http import HttpResponse, Http404, JsonResponse
from django.forms.models import model_to_dict
import json

from .models import Continent, Country


def continent_json(request, continent_code):
    """ Write your answer in 7.2 here. """
    try:
        print("CONTINENT QuerySet: ", Continent.objects.filter(
            code__exact=continent_code).values("countries"))
        continent_data = json.dumps( list(Continent.objects.filter(
            code__exact=continent_code).values("countries") ) )
        print("CONTINENT JSON: ",continent_data)
    except Continent.DoesNotExist:
        raise Http404("Requested continent does not exist.")

    # If JSONP
    if "callback" in request.GET:
        continent_data = "{}({})".format(
            request.GET["callback"],
            continent_data
            )
        return HttpResponse(continent_data)

    # Normal JSON
    return HttpResponse(continent_data, content_type="application/json")


def country_json(request, continent_code, country_code):
    """ Write your answer in 7.2 here. """
    try:
        #print("COUNTRY_OBJECT: "Country.objects.filter(code__exact=country_code).values())
        print("MODEL_LIST: ",list(Country.objects.filter(code__exact=country_code).values("capital","population","area")))
        country_data = json.dumps( list(Country.objects.filter(
            code__exact=country_code).values("code","name") ) )
        print("COUNTRY DATA: ", country_data)

    except Country.DoesNotExist:
        raise Http404("Requested country does not exist.")

    # If JSONP
    if "callback" in request.GET:
        country_data = "{}({})".format(
            request.GET["callback"],
            country_data
            )
        return HttpResponse(country_data)

    # Normal JSON
    return HttpResponse(country_data, content_type="application/json")

Однако это не дает желаемых результатов: данные на самом деле не возвращаются в виде JSON (P), нокак диктат или список.Это большой код, который нужно пролистать, но я нахожусь в своем уме.

Что я делаю не так?

1 Ответ

0 голосов
/ 14 октября 2018

Из того, что вы объяснили в чате:

Вам нужно изменить свои представления на что-то вроде этого

country_data = json.dumps(dict(Country.objects.filter(
        code__exact=country_code).values("code","name")[0])))

и для просмотра континента:

continent = Continent.objects.get(code__exact=continent_code)
country_data = json.dumps(dict(continent.countries.values_list('code', 'name')))
...