【问题标题】:Restangular, Django REST and relationsRestangular、Django REST 和关系
【发布时间】: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 提供者处定义,并且数据已经在 J​​S 数组中结构化)。我会整天写解析器+反序列化器。 :/ (或者有一些我不知道的不错的 JS 库吗?)

标签: django angularjs rest django-rest-framework restangular


【解决方案1】:

我相信最好的方法是创建嵌套的 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; 
})

【讨论】:

    猜你喜欢
    • 2016-01-10
    • 2016-07-03
    • 2013-10-20
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    相关资源
    最近更新 更多