django-tastypie 初步实现

2018-04-20  本文已影响20人  nine_9

重写两个方法def get_object_list(self, request):

request所对应的就是view中的request

写自己的逻辑,返回想要的数据

                        def obj_get_list(self, bundle, **kwargs):

                            return self.get_object_list(bundle.request)

class Price1(Resourse):自己定义模型,写自己所需要的字段

class meta:设置属性。

calss BaseJsonModel(): 创建一个Json数据的数据集

app下的model:

class Goods(models.Model):

    name = models.CharField(max_length=10)

    date = models.DateTimeField()

    price = models.FloatField()

根目录下的url:

v1_api = Api(api_name='v1')

v1_api.register(Price())

v1_api.register(Price1())

urlpatterns = [

    url(r'^admin/', include(admin.site.urls)),

    url(r'^api/', include(v1_api.urls)),

]

app下的自己写一个py文件:

class BaseJsonModel(object):

    '''

    We need a generic object to shove data in/get data from for modelResource.

    '''

    def __init__(self, initial=None):

        self.__dict__['_data'] = {}

        if hasattr(initial, 'items'):

            self.__dict__['_data'] = initial

    def __getattr__(self, name):

        return self._data.get(name, None)

    def __setattr__(self, name, value):

        self.__dict__['_data'][name] = value

    def to_dict(self):

        return self._data

#定义并返回的Json格式的数据集(主要)

class Price1(Resource):

    '''

    用ModelResource实现

    '''

    max_price = fields.CharField(attribute='max_p')  # 最大值

    min_price = fields.CharField(attribute='min_p')  # 最小值

    avg_price = fields.CharField(attribute='avg_p')  # 平均

    # datet = fields.CharField(attribute='datet')

    # gid = fields.CharField(attribute='gid')

    class Meta:

        # objects_class = Goods

        resource_name = 'price1'

        # queryset = Goods.objects.filter(name='good1')

        queryset = Goods.objects.all()

        limit = 10

        authorization = Authorization()

    def get_object_list(self, request):

        good = request.GET['good']

        start_time = request.GET['start']

        end_time = request.GET['end']

        # queryset = Goods.objects.filter(name=good).order_by('-date')

        queryset = Goods.objects.filter(

            name=good, date__range=(start_time, end_time))

        objects = queryset.values('name').annotate(

            max_p=Max('price'),

            min_p=Min('price'),

            avg_p=Avg('price'),

            # datet=('date'),

        )

        print(objects)

        results = []

        for obj in objects:

            print(obj['name'])

            object = BaseJsonModel()  # 创建数据集

            object.name = obj['name']

            object.max_p = obj['max_p']

            object.min_p = obj['min_p']

            object.avg_p = obj['avg_p']

            # object.datet = obj['datet']

            results.append(object)

            # print(result)

            # for i in results:

            #    print(i.name)

        return results

    def obj_get_list(self, bundle, **kwargs):

        return self.get_object_list(bundle.request)

上一篇下一篇

猜你喜欢

热点阅读