如何用Json发布ManyToMany数据?

时间:2019-03-24 10:44:15

标签: python django-rest-framework

我有这样的数据。
enter image description here

model.py

from django.db import models


class Diet(models.Model):
    date = models.CharField(max_length=20)
    building = models.CharField(max_length=40)
    location = models.CharField(max_length=40)
    restaurants = models.ManyToManyField('Restaurant')

    def __str__(self):
        return self.building


class Restaurant(models.Model):
    name = models.CharField(max_length=40)
    menus = models.ManyToManyField('DietMenu')

    def __str__(self):
        return self.name


class DietMenu(models.Model):
    name = models.CharField(max_length=256)
    price = models.CharField(max_length=20)

    def __str__(self):
        return self.name

api.py

from .models import Diet
from .models import Restaurant
from .models import DietMenu
from rest_framework import serializers, viewsets


class DietMenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = DietMenu
        fields = ('name', 'price')


class DietMenuViewSet(viewsets.ModelViewSet):
    queryset = DietMenu.objects.all()
    serializer_class = DietMenuSerializer


class RestaurantSerializer(serializers.ModelSerializer):
    menus = DietMenuSerializer(many=True, read_only=True)
    class Meta:
        model = Restaurant
        fields = ('name', 'menus')


class RestaurantViewSet(viewsets.ModelViewSet):
    queryset = Restaurant.objects.all()
    serializer_class = RestaurantSerializer


class DietSerializer(serializers.ModelSerializer):
    restaurants = RestaurantSerializer(many=True, read_only=True)
    class Meta:
        model = Diet
        fields = ('date', 'building', 'location', 'restaurants')


class DietViewSet(viewsets.ModelViewSet):
    queryset = Diet.objects.all()
    serializer_class = DietSerializer

然后我得到了这样的数据的json。
enter image description here

import requests


class DjangoJson(object):
    def __init__(self):
        self.url = "url"

    def set_diet_date(self):
        self.url = "http://localhost:8000/api/v1/diet/?format=json"

    def get(self):
        self.set_diet_date()
        request = requests.get(self.url)
        document = request.json()
        return document

    def post(self, param):
        requests.post(self.url, json=param)


if __name__ == "__main__":
    json = DjangoJson()
    doc = json.get()[0]
    json.post(doc)

然后我通过使用请求库发布此json。但是餐厅字段为空。
enter image description here

有没有一种方法可以用Json张贴ManyToMany数据? 谢谢。

0 个答案:

没有答案