我想通过传递的ID和年份来过滤URL的通用API视图。传递的ID在模型上,但是年份是嵌套的。
数据结构示例如下:
This is one Building Group:
[
{
"description": "BG1",
"buildings": [
{
"id": 1,
"name": "Building13",
"demandheat_set": [
{
"id": 1,
"year": 2019,
},
{
"id": 2,
"year": 2013,
},
{
"id": 2,
"year": 2013,
}
我想针对一个URL过滤此视图,以仅显示例如2013年的Demandheat_set。
我关注了有关过滤的文档,可以按组进行过滤。这就是我要从上面获取示例数据的目的:
class BGHeat(ListAPIView):
serializer_class = BGHeatSerializer
def get_queryset(self):
building_group_id = self.kwargs['building_group_id']
building_group_objects = BuildingGroup.objects.filter(id=building_group_id)
)
return building_group_objects
好极了,我可以按建筑组的ID进行过滤,并使用以下URL取回我上面发布的示例数据:
path('test/<int:building_group_id>/', BGHeat.as_view(),
name="")
现在,我想按嵌套的年份进行过滤,但是我无法使用它。...
我尝试过:
URLs
path('test/<int:building_group_id>/<int:year>/', BGHeat.as_view(),
name="")
现在,我想将查询集更改为仅包含我需要的数据:
def get_queryset(self):
"""
This view should return a list of all the purchases for
the user as determined by the username portion of the URL.
"""
building_group_id = self.kwargs['building_group_id']
passed_year = self.kwargs['year']
building_group_objects = BuildingGroup.objects.filter(id=building_group_id)
building_group_list = []
for items in building_group_objects:
building_group_list.append(items)
buildings_list = []
for item in building_group_list:
buildings_list.append(item.buildings)
demand_cool_list = []
for item in buildings_list:
demand_cool_item = item.demandcool_set.filter(year=passed_year).values(
'building_id', 'year', 'demand')
demand_cool_list.append(demand_cool_item)
print(demand_cool_list)
return demand_cool_list
这给了我ManyRelatedManager' object has no attribute 'demandcool_set'
现在,在跟踪整个兔子之前,我想知道我是否遵循正确的道路?我想做的事甚至有可能吗?
如果可以,我该如何返回我需要的列表?
非常感谢您的帮助!在此先感谢!
这是我的模特:
class BuildingGroup(models.Model):
buildings = models.ManyToManyField(Building, default=None, blank=True)
class Building(models.Model):
name = models.CharField(max_length=120, null=True, blank=True)
class DemandHeat(models.Model):
year = models.PositiveIntegerField(default=default_year())
building = models.ForeignKey(Building, on_delete=models.CASCADE)