使用嵌套字典保存django模型的方法

时间:2015-12-31 01:35:34

标签: python django dictionary django-models

我会尝试尽可能简单:

我有2个模特

from django.db import models


class OrderDetail(models.Model):
    product = models.CharField(max_length=100)
    price = models.CharField(max_length=50)


class Order(models.Model):
    url = models.CharField(max_length=255, unique=True)
    loaded_info = models.BooleanField(default=False)
    status = models.CharField(max_length=100, null=True)
    details = models.OneToOneField(OrderDetail)

我想用这样的字典保存:

data = {
    "order": {
        "url": "http://stackoverflow.com/",
        "loaded_info": True,
        "status": "complete",
        "details": {
            "product": "Fresh answer",
            "price": "50 points"
        }
    }
}

我想做一些接近的事情:

order = Order(**data).save()

使用一行保存OrderOrderDetail

1 个答案:

答案 0 :(得分:0)

查看https://docs.djangoproject.com/en/1.9/topics/serialization/

在这种情况下,您可以执行以下操作:

qs = Order.objects.select_related('details').get(pk=1)
data = serializers.serialize("json", qs)