我会尝试尽可能简单:
我有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()
使用一行保存Order
和OrderDetail
。
答案 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)