我想构建以下树:
顶
使用mptt django tastypie(参见下面的模型和资源代码)。 而不是创建两个子项到'Top'记录,它创建两个树(不同的tree_id),son1的parent_id是Null。
head = {"content-type": "application/json"}
payload = { "user": {'id': 1},
"parent": {'id': None},
"name": 'Top' }
r = requests.post("{host}/api/v1/account/",
data=json.dumps(payload), headers=head)
# the id of the created record is e.g. 10
payload = { "user": {'id': 1},
"parent": {'id': 10},
"name": 'son1' }
r = requests.post("{host}/api/v1/account/",
data=json.dumps(payload), headers=head)
payload = { "user": {'id': 1},
"parent": {'id': 10},
"name": 'son2' }
r = requests.post("{host}/api/v1/account/",
data=json.dumps(payload), headers=head)
注意: 如果我在有效载荷中使用完整的uri。 e.g。
payload = { "user": '/api/v1/user/1/',
"parent": '/api/v1/account/10/',
"name": 'son1' }
那就行了。
模特:
class Account(MPTTModel):
user = models.ForeignKey(User)
name = models.CharField(max_length=20)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
class Meta:
verbose_name_plural = 'Accounts'
def __unicode__(self):
return ' Account: %s' % self.name
class AccountResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
children = fields.ToManyField('self', 'children', null=True, full=True)
parent = fields.ToOneField('self', 'parent', null=True)
class Meta:
serializer = PrettyJSONSerializer()
allowed_methods = ['get', 'post', 'put', 'delete']
queryset = Account.objects.all().select_related('parent')
include_resource_uri = False
always_return_data = True
filtering = {
"id": ('exact'),
"user": ('exact'),
"name": ('exact'),
"parent": ('exact'),
"level": ('exact'),
}
authentication = Authentication()
authorization = Authorization()
fields = []
excludes = ['parent', 'rght', 'lft', 'level', 'tree_id']
为了仅使用id,我应该更改什么,而不指定完整的uri并使其正常工作?
更新:我意识到当我使用上面的JSON代码(而不是完整的uri)时会发生其他奇怪的事情,用户表中的密码字段变为NULL。它看起来像某种内存损坏。