重寫兩個方法:def get_object_list(self, request):
request所對應的就是view中的request
寫自己的邏輯捧书,返回想要的數(shù)據
? ????????????????????? def obj_get_list(self, bundle, **kwargs):
? ? ? ????????????????????? return self.get_object_list(bundle.request)
class Price1(Resourse):自己定義模型袱蚓,寫自己所需要的字段
class meta:設置屬性。
calss BaseJsonModel(): 創(chuàng)建一個Json數(shù)據的數(shù)據集
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格式的數(shù)據集(主要)
class Price1(Resource):
? ? '''
? ? 用ModelResource實現(xiàn)
? ? '''
? ? 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()? # 創(chuàng)建數(shù)據集
? ? ? ? ? ? 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)