我有关于序列化和关系的问题。我想获取对象而不是对象 ID。(Django 1.4)
这段代码在我看来:
serializers.serialize("json", Projects.objects.all(), indent=5, use_natural_keys=True)
序列化项目后,我得到:
[
{
"pk": 1,
"model": "work.projects",
"fields": {
"count": 3,
"date": "2013-02-03T09:43:20.474Z",
"client": 1,
"status": false,
"service": 1
}
}
]
这是我的模型:
from django.db import models
class ServicesManager(models.Manager):
def get_by_natural_key(self, name, price, unit):
return self.get(name=name, price=price, unit=unit)
class Services(models.Model):
objects = ServicesManager()
name = models.CharField(max_length=200)
price = models.IntegerField()
unit = models.CharField(max_length=50)
class CustomersManager(models.Manager):
def get_by_natural_key(self, name, city, street, post_code, phone, nip):
return self.get(name=name, city=city, street=street, post_code=post_code, phone=phone, nip=nip)
class Customers(models.Model):
objects = CustomersManager()
name = models.CharField(max_length=200)
city = models.CharField(max_length=200)
street = models.CharField(max_length=200)
post_code = models.CharField(max_length=100)
phone = models.CharField(max_length=200)
nip = models.CharField(max_length=200)
class Projects(models.Model):
client = models.ForeignKey(Customers)
service = models.ForeignKey(Services)
count = models.IntegerField()
date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(null=False)
def natural_key(self):
return (self.count, self.date, self.status,) + self.service.natural_key() + self.client.natural_key()
natural_key.dependencies = ['work.services', 'work.customers']
这是解决方案(模型):
from django.db import models
class Services(models.Model):
name = models.CharField(max_length=200)
price = models.IntegerField()
unit = models.CharField(max_length=50)
def natural_key(self):
return (self.name,self.price,self.unit)
class Customers(models.Model):
name = models.CharField(max_length=200)
city = models.CharField(max_length=200)
street = models.CharField(max_length=200)
post_code = models.CharField(max_length=100)
phone = models.CharField(max_length=200)
nip = models.CharField(max_length=200)
def natural_key(self):
return (self.name,self.city,self.street,self.post_code,self.phone,self.nip)
class Projects(models.Model):
client = models.ForeignKey(Customers)
service = models.ForeignKey(Services)
count = models.IntegerField()
date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(null=False)
def natural_key(self):
return (self.count, self.date, self.status, self.service.natural_key(), self.client.natural_key())
并查看代码(对于 UTF-8)
serializers.serialize("json", Projects.objects.all().filter(pk=1), indent=3, use_natural_keys=True, ensure_ascii=False)