django - Restangular、Django REST 和关系

标签 django angularjs rest django-rest-framework restangular

我正在使用 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() 返回的 promise ,但 $object 用于解释这一点更短)
$scope.countries = [];
$scope.cities = [];
$scope.customers = [];

Restangular.all( "countries" ).getList().$object;
Restangular.all( "cities" ).getList().$object;
Restangular.all( "customers" ).getList().$object;

这是一个城市响应的示例:( 所有 ,无一异常(exception),模型都包含一个 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 等)中改变我做事的方式。

最佳答案

我相信最好的方法是创建嵌套的 serailizers。您必须在帖子上切换序列化程序,但在列表中并检索这样的序列化程序会起作用。

class CountrySerializer(serializer.ModelSerializer):
    class Meta:
        model = Country


class CitySerializer(serializer.ModelSerializer):
    country = CountrySerializer()
    class Meta:
        model = City

class CustomerSerializer(serializer.ModelSerializer):
    city = CitySerializer()
    class Meta:
        model = Customer

class CustomerViewSet(viewsets.ModelViewSet):
    model = Customer
    serializer_class = CustomerSerializer
    queryset = Customer.objects.all()

然后你的 Restangular 只需要点击 api 并且对象被正确嵌套
Restangular.all('costumers').one(1).get().then(function(response) {
    $scope.costumer = response; 
})

关于django - Restangular、Django REST 和关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25038809/

相关文章:

javascript - Couch DB 中的 Erlang View

python - html中的if语句(基于搜索查询)

javascript - 使用 AngularJS 过滤 ng-repeat 中的特殊字符?

rest - symfony 形式 + fos 休息

javascript - 扩展 AngularJs 指令

javascript - AngularJS:你能从多个 $scope.$apply() 调用中得到 'digest in progress' 错误吗?

PHP fatal error : Class 'Slim' not found in

python - celery ,作为 worker 和调度程序的推荐方法是什么?

python - Django登录 "?next="只保存一个GET参数

在 heroku 上使用 nested_inline 时 collectstatic 期间出现 Django 错误