如何使用AngularJs基于过滤器获取Django模型(数据库表)中的所有对象

时间:2016-09-29 07:43:17

标签: python angularjs django

您好我有一个Django模型如下:

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Journal(models.Model):
    name = models.CharField(max_length=120)
    created_by = models.ForeignKey(User, related_name='+')
    date_created = models.DateTimeField(auto_now=False, auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True, auto_now_add=False )

    def __unicode__(self):
        return (self.name)

我的角度如下:

var app = angular.module("journalApp", []);
    app.controller("myCtrl", function($scope) {

});

如何在AngularJs中进行查询,以便根据登录用户从Django模型中获取所有对象?伙计们好吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

要检索所有日记对象,您可以使用django REST framework创建视图,并在角度方面创建Service并使用$resource$http或转到推荐{ {3}}从django rest api中检索数据。 restangular也可用于身份验证。

答案 1 :(得分:1)

在服务器端尝试此方法

import json
from django.http import JsonResponse
from django.views.generic View

from .models import Journal


class JSONResponseMixin(object):
    """
    A mixin that can be used to render a JSON response.
    """
    def render_to_json_response(self, context, **response_kwargs):
         """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        return JsonResponse(
        self.get_data(context),
        **response_kwargs
        )

    def get_data(self, context):
        """
        Returns an object that will be serialized as JSON by json.dumps().
        """
        return context

class JournalView(JSONResponseMixin, View):

    def get(self, request, *args, **kwargs):
        response_data = {}
        response_data['data'] = Journal.objects.filter(created_by=self.request.user).values()
        return self.render_to_json_response(dict(response=response_data))

当然,您需要将视图添加到您的urls.py

客户端尝试此方法

var app = angular.module("journalApp", []);
    app.controller("myCtrl", function($scope, $http) {

    var url = "/your-url-to-view"; # {% url 'init_data' %}}

    $scope.initData = function(){
        $http.get(url).then(function(data){
            $scope.data = data.data.response;
        })
    }

});