【问题标题】:Iterating through database objects and rendering them to the template遍历数据库对象并将它们呈现给模板
【发布时间】:2014-08-16 00:12:41
【问题描述】:

我有一些数据正在尝试提供给模板。这是试图这样做的视图的 sn-p:

   def get(self, request, *args, **kwargs):
        user = User.objects.get(username=request.user.username)
        beac_data = user.get_profile().owned_beacons.all()
        for beacon in beac_data:
            beacon_data_name = beacon.name
            beacon_data_factory_id = beacon.factory_id
            beacon_data_location = beacon.location
            beacon_data_visible = beacon.visible
            beacon_data_config_id = beacon.config_id
        #more code here

        return render(request, self.template_name, {
            'form': self.form, 
            'location': location, 
            'beacon_data_name': beacon_data_name,
            'beacon_data_factory_id': beacon_data_factory_id,
            'beacon_data_location': beacon_data_location,
            'beacon_data_visible': beacon_data_visible,
            'beacon_data_config_id': beacon_data_config_id,
        }) 

如图所示,我遍历数据库中的对象,并在我的html文件中提供相关的模板标签:

           {{ beacon_data_name }}
           {{ beacon_data_factory_id }}
           {{ beacon_data_location }}
           {{ beacon_data_visible }}
           {{ beacon_data_config_id }}

模板标签有效,但它只呈现第一个对象的信息。为什么它不返回数据库中所有对象的所有数据?一些帮助将不胜感激。

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    在上下文中传递beac_data 并在模板中遍历它:

    def get(self, request, *args, **kwargs):
        user = User.objects.get(username=request.user.username)
        beac_data = user.get_profile().owned_beacons.all()
    
        return render(request, self.template_name, {
            'form': self.form, 
            'location': location, 
            'beac_data': beac_data
        }) 
    

    然后,在模板中:

    {% for beacon in beac_date %}
        {{ beacon.name }}
        {{ beacon.factory_id }}
        {{ beacon.location }}
        {{ beacon.visible }}
        {{ beacon.config_id }}
    {% endfor %}
    

    【讨论】:

    • @alexce 的解决方案是正确的,但只是为了解释发生了什么:问题是当您在 for 循环中遍历 beac_data 时,您将数据存储到同一组变量中。您正在覆盖之前的值的循环的每次迭代——例如,beacon_data_name 在每次循环运行时都会被覆盖,并且只会存储 beacon.name 的最后一次迭代。上面的解决方案可能是处理这个问题的最好方法。
    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多