gpt4 book ai didi

django - Restangular、Django REST 和关系

转载 作者:行者123 更新时间:2023-12-04 20:06:30 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com