加载模型和相关数据

时间:2014-11-06 14:21:54

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


我目前正在开发WebApp

服务器端:

客户方:

<小时/> 我的问题是关于与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

我希望有一种方法可以轻松地完全映射我的对象,我并不反对Restangular库以外的任何其他方式。

1 个答案:

答案 0 :(得分: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有效负载,以获取所需数据。