在Django中的for循环中使用两个查询集?

时间:2019-01-27 13:45:24

标签: django django-queryset

我正在为Django中的组织构建一个库存管理应用。该组织有多个房间,每个房间的架子上都有存储区。

我正在尝试使用for循环显示每个房间中可用的存储空间数量以及已占用的存储空间数量。到目前为止,我已经设法显示了这些数据,但是我必须使用两个单独的for循环和两个查询集“ Vacant_location_data”和“ Occupied_location_data”。 See attached image for how this is currently displaying.

如果可能的话,我希望能够为此使用一个for循环,因为这将允许我在图表中绘制此数据。这可能吗?

下面是我的代码的简化版本:

我的模型。py:

class Location(models.Model):
    loc_room = models.CharField()
    loc_section = models.IntegerField()
    loc_shelf = models.CharField()


class Box(models.Model):
    box_contents = models.CharField() 
    Location = models.OneToOneField()

我的views.py:

def dashboard(request):
    Vacant_location_data = Location.objects.values('loc_room').filter(box__isnull=True).annotate(nempty=Count('id')).order_by('loc_room')
    Occupied_location_data = Location.objects.values('loc_room').filter(box__isnull=False).annotate(nempty=Count('id')).order_by('loc_room')

我的HTML:

<div>

  {% for each_room in Vacant_location_data %}

      {
        <p>"Room name": "Room {{each_space.loc_room}}"</p>
        <p>"Free Space": {{ each_room.nempty }}</p>
      },

  {% endfor %}

</div>


<div>

  {% for each_room in Occupied_location_data %}
      {
        <p>"Room name": "Room {{each_room.loc_room}}"</p>
        <p>"Occupied Space": {{ each_room.nempty }}</p>
      },
  {% endfor %}

</div>

1 个答案:

答案 0 :(得分:0)

我在外部资源的帮助下设法解决了此问题。对于任何有类似问题的人,这都是我在views.py中所做的更改:

def dashboard(request):
    Vacant_location_data = list(Location.objects.values('loc_room').filter(box__isnull=True).annotate(nempty=Count('id')).order_by('loc_room'))
    Occupied_location_data = list(Location.objects.values('loc_room').filter(box__isnull=False).annotate(nempty=Count('id')).order_by('loc_room'))

    for i, vacant in enumerate(Vacant_location_data):
        vacant['occupied'] = Occupied_location_data[i]['nempty']

return render(request, 'inventory_management_app/user_profile.html' ,
{"Vacant_location_data":Vacant_location_data,
"Occupied_location_data":Occupied_location_data,})

现在,使用HTML,我可以使用一个for循环显示每个房间的已占用空间和未占用空间:

{% for each_space in Vacant_location_data %}
        {
            "name": "{{ each_space.loc_room }}",
            "id": "{{ each_space.loc_room }}",
            "data":

            [
                [
                    "Free space",
                    {{ each_space.nempty }}
                ],

                [
                    "Total Used Space",
                    {{ each_space.occupied }}
                ],


            ]
        },

        {% endfor %}