在django rest framework

时间:2017-03-29 20:20:56

标签: django django-rest-framework

我收到一个Json响应将其保存在我的数据库中,我需要获取line_items对象中的项目。如果我删除模型中的line_items属性,我的Serializer和View工作正常,但是当我尝试获取该对象并将其保存在数据库中时,没有任何反应。也许我在序列化器中遗漏了一些东西?

Json结构:

{
    "id": 123456,
    "email": "jon@doe.ca",
    "created_at": "2017-03-29T15:56:48-04:00",
    "line_items": [
        {
            "id": 56789,
            "title": "Aviator sunglasses",
            "quantity": 1
         },

    {
        "id": 98765,
        "title": "Mid-century lounger",
        "quantity": 1
    }

    ]
}

我的模特:

class Line(models.Model):
    title = models.CharField(max_length=100)
    quantity = models.IntegerField()


class Order(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField()
    total_price = models.DecimalField(max_digits=6,decimal_places=2)
    line_items = models.ForeignKey(Line)

My Serializer:

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

我的观点:

@api_view(['POST'])
def orders(request):
    if request.method == 'POST':
        json_str = json.dumps(request.data)
        resp = json.loads(json_str)
        serializer = OrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

3 个答案:

答案 0 :(得分:1)

您的回复中的字段密钥doctrine: dbal: driver: pdo_mysql host: '%database_host%' port: '%database_port%' dbname: '%database_name%' user: '%database_user%' password: '%database_password%' charset: latin1 default_table_options: collate: "latin1_swedish_ci" 中有一个列表,根据您的模型,您无法容纳表格中的数据,您需要line_items之间的关系{ {1}}和ManyToMany

Order

并在您的序列化程序中,

Line

答案 1 :(得分:0)

我认为你应该向OrderSerializer添加一个显式的line_items字段。像这样:

class OrderSerializer(ModelSerializer):
    line_items = LineSerializer(many=True)
    class Meta:
        model = Order
        fields = '__all__'

答案 2 :(得分:0)

只需在序列化程序中添加depth = 1即可。它会 -

class OrderSerializer(ModelSerializer):

    class Meta:
        depth = 1
        fields = '__all__'