【发布时间】:2014-09-22 05:05:34
【问题描述】:
我正在使用 Django REST Framework 对使用大量模型关系的 REST API 进行建模。
在前端级别使用 AngularJS 和 Restangular 解决这些关系的简单而好的方法是什么?
型号
这是我的部分模型的样子:
class Country( Model ):
name = CharField( max_length = 256 )
class City( Model ):
name = CharField( max_length = 256 )
postal_code = CharField( max_length = 16 )
country = ForeignKey( "Country" )
class Customer( Model ):
first_name = CharField( max_length = 256 )
last_name = CharField( max_length = 256 )
city = ForeignKey( "City" )
获取数据
以下 JavaScript 代码显示了我如何加载数据:(我实际上使用了 all() 返回的承诺,但 $object 更短,可以解释这一点)
$scope.countries = [];
$scope.cities = [];
$scope.customers = [];
Restangular.all( "countries" ).getList().$object;
Restangular.all( "cities" ).getList().$object;
Restangular.all( "customers" ).getList().$object;
这是一个城市响应的示例:(all,无一例外,模型都包含一个 id 字段)
[{"id": 1, "name": "Bocholt", "postal_code": "46397", "country": 1}]
显示数据
最后是用于显示数据的 AngularJS 部分;你在这里看到的代码就是我想使用它的方式:
<table>
<tbody>
<tr ng-repeat="customer in customers">
<td>{{ customer.first_name }}</td>
<td>{{ customer.last_name }}</td>
<td>{{ cities[customer.city].name }}</td>
<td>{{ countries[cities[customer.city].country].name }}</td>
</tr>
</tbody>
</table>
诚然,嵌套语句看起来有点难看,但考虑到原始数据保持不变,我可以这样做。
不幸的是,代码确实(当然)不起作用。解决这种关系的好方法是什么?
提示:我愿意在任何涉及的框架/程序(Django、Django REST、AngularJS、Restangular 等)中改变我的做事方式。
【问题讨论】:
-
从您的 API 响应中创建模型。这样一来,您就不必到处使用 dict 访问弄脏手指了。
-
@limelights 你的意思是我应该解析来自 API 的数据,将其打包成对象并链接对象以表示关系?这会起作用,但它也会在客户端代码中添加大量冗余(模型已经在 API 提供者处定义,并且数据已经在 JS 数组中结构化)。我会整天写解析器+反序列化器。 :/ (或者有一些我不知道的不错的 JS 库吗?)
标签: django angularjs rest django-rest-framework restangular