2014-11-06 88 views
0


我目前工作的一個Web應用程序負荷模型和相關數據

服務器端:

客戶端:


我的問題是關於與Restangular庫中的關係映射。

例:

controller.js

Restangular.all('Cars').getList().then(function(_cars){ 
    $scope.cars= _cars; 
}); 


_list.html

<tr ng-repeat="car in cars"> 
    <td>{[project.id]}</td> 
    <td>{[project.owner.name]}</td> <!-- owner is not mapped, (project.owner == ID) --> 
</tr> 


我的代碼:

Django的:models.py

class Person(models.Model): 
    #.... 
    name = models.CharField(db_index=True, max_length=200) 

class Car(models.Model): 
    #.... 
    owner = models.ForeignKey(Person, blank=True, null=True) 

Django的:serializers.py

class CarSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Car 
     fields = ('id', /*...*/, 'owner') 

Django的:view.py

class CarList(generics.ListCreateAPIView): 
    queryset = Car.objects.all() 
    serializer_class = CarSerializer 

我希望有一種方法充分映射我的對象easil y,我不反對Restangular圖書館。

回答

1

看起來你需要定義一個串行的Person並指它在你的CarSerializer

class PersonSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = models.Person 

    fields = ('id', ...) 


# Then use that serializer in CarSerializer: 
class CarSerializer(serializers.ModelSerializer): 
    owner = PersonSerializer(source='owner') 

    class Meta: 
     model = Car 
     fields = ('id', /*...*/, 'owner') 

使用DRF可瀏覽API來獲取所需的數據檢查JSON有效載荷。

+0

完美!複製/過去的作品100% – 2014-11-07 08:57:08