Restangular、Djangoの休息と関係
-
21-12-2019 - |
質問
多くのモデル関係を使用するREST APIをモデル化するためのDjango RESTフレームワークを使用しています。
AngularJSとRestangulularを使用してフロントエンドレベルでそれらの関係を解決するための簡単で良い方法は何ですか?
モデル
これは私のモデルの一部のように見えるかです。
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コードは、データをロードする方法を示しています。
$scope.countries = [];
$scope.cities = [];
$scope.customers = [];
Restangular.all( "countries" ).getList().$object;
Restangular.all( "cities" ).getList().$object;
Restangular.all( "customers" ).getList().$object;
.
これは cities reponseの例です。( 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>
.
確かに入れ子のステートメントは少し醜いですが、元のデータがそのまま残らないという事実を考えると、そのようにうまくいます。
残念ながら、(もちろん)は動作しません。そのような種類の関係を解決するための良い方法は何ですか?
clue:私は、関与するフレームワーク/プログラム(Django、Django Rest、AngularyJS、Restangularなど)のいずれかで、物事をやることをやることができます。
解決
私はこれを行うための最良の方法は、ネストされたSerailizersを作成することです。POST上のシリアライザを切り替える必要がありますが、リストにはこのようなシリアライザを取得する必要があります。
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()
.
とそれからあなたのRestangululはAPIを押して、オブジェクトは正しく入れ子になっています
Restangular.all('costumers').one(1).get().then(function(response) {
$scope.costumer = response;
})
. 所属していません StackOverflow