我有一个父资源,其中一个attrbiute可以有多个子元素,而另一个属性可以有一个以上子元素。它们看起来像这样:
class RouteResource(ModelResource):
creator = fields.ForeignKey(UserProfileResource, 'creator', full=True)
towns = fields.ToManyField(TownResource, 'towns', full=True, null=True)
模型是:
class Route(models.Model):
name = models.CharField(max_length=50)
description = models.CharField(max_length=500)
average_rate = models.FloatField(null=True, blank=True, default=0)
date_created = models.DateTimeField(auto_now=True, auto_now_add=True)
creator = models.ForeignKey(UserProfile)
towns = models.ManyToManyField(Town)
def __unicode__(self):
return self.name
第二个资源是:
class MarkerResource(MultipartResource, ModelResource):
route = fields.ForeignKey(RouteResource, 'route')
picture = fields.FileField(attribute="picture", null=True, blank=True)
它的模型是:
class Marker(models.Model):
picture = models.FileField(upload_to=get_upload_file_name, null=True, blank=True, max_length=500)
description = models.CharField(max_length=500)
longitude = models.FloatField()
latitude = models.FloatField()
order = models.IntegerField()
route = models.ForeignKey(Route)
好的,现在,我可以成功地添加城镇路线,我的资源看起来不错:
{
. . .
. . .
"towns": [
{
"id": 1,
"name": "my town",
"resource_uri": "/api/v1/town/1/"
}
]
}
现在我想通过POST添加一个预定义路由作为外键的标记:
{
"description": "Center of earth",
"latitude": 0,
"longitude": 0,
"order": 1,
"picture": null,
"route": {
"id":59
}
}
之后我的标记成功添加到正确的路线,但我添加了路线的城镇被删除,所以我的路线没有任何城镇:
{
"towns": []
}
答案 0 :(得分:1)
你可以:
route: "/api/v1/route/59/"
hydrate_route
的{{1}}方法,以返回给定字典传递的对象。MarkerResource
创建一个自定义字段,该字段将实现自定义fields.ForeignKey
行为。