简体   繁体   English

如何迭代Django字典中的外键?

[英]How can I iterate over foreign keys in a Django dictionary?

I am pretty new to programming and have a question about iterating over foreign keys in my Django view file. 我对编程很新,并且有关于在Django视图文件中迭代外键的问题。

models.py models.py

class Site(models.Model):
    other fields.......
    sensor = models.ForeignKey("Sensor", blank=True, null=True)
    slug = models.SlugField(unique=True)

views.py views.py

def site(request, site_name_slug):

    context_dict = {}

    empty_field = "<font color='LightGray'>No Data</font>"


    try:
        site = Site.objects.values().get(slug=site_name_slug)
        context_dict['site_slug'] = site_name_slug

        for key, value in site.iteritems():
            if value:
                context_dict[key] = value
            else:
                context_dict[key] = empty_field

Is it possible to do add something like this? 可以添加这样的东西吗?

for key, value in (site.sensor).iteritems():
    if value:
        context_dict['sensor_%s' % key] = value
    else:
        context_dict['sensor_%s' % key] = value

So that I don't have to use if/else or try/except for every field in the sensor object. 这样我就不必对传感器对象中的每个字段使用if / else或try / except。

No, ForeignKeys provide one-to-many relationships. 不, ForeignKeys提供一对多的关系。

In your model a given Site will only ever have at most one sensor. 在您的模型中,给定的Site 最多只能有一个传感器。 There is nothing to iterate over, so what you are asking doesn't make sense. 没有什么可以迭代,所以你问的是没有意义的。


There is no need to specifically iterate through all of the sensor s fields to access them in the template, if you pass the page site into the template, for example as current_site you can access the sensor like so: 如果将页面site传递到模板中,则无需专门遍历所有sensor的字段以在模板中访问它们,例如,作为current_site您可以访问传感器,如下所示:

{{ current_site.sensor }}

To access a sensors field, (for example if a sensor had a field named "value") just append that, like so: 要访问传感器字段,(例如,如果传感器有一个名为“value”的字段),只需添加,如下所示:

{{ current_site.sensor.value }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM