2015-02-10 36 views
0

在Django中,我使用以下代碼從LocationImage模型中獲取與位置相關的圖像。在Django中查找一組相關項目

{% for location in locations %} 
{% for image in location.locationimage_set.all %} 
etc 

如果該位置是一個區域,並有該區域無圖像,我希望能夠得到的圖像在該區域的城市,通過仍僅參照該區域。

城市也是定位模型的一部分,設置爲區域和related_name =「location_region」

如何做到這一點任何想法的區域場?

例如,如果我在LocationImage模型中有一個區域字段,那麼我將如何引用區域字段中的該區域id的所有LocationImages集合,而不是主ID字段。

按照要求,型號:

class LocationImage(models.Model): 
    location = models.ForeignKey(Location) 
    imagelink = models.URLField(max_length=500, null=True) 

class Location(models.Model): 
    id = models.IntegerField(primary_key=True) 
    name = models.CharField(max_length=200, db_index=True, verbose_name="ascii name") 
    slug = models.SlugField(max_length=200) 
    locationtype = models.CharField(max_length=50) 
    region = models.ForeignKey('self', null=True, blank=True, related_name='location_region') 
    country = models.ForeignKey('self', null=True, blank=True, related_name='location_country') 

其中的locationType = '城市',「區域或 '國家'

+1

請顯示您的模型代碼。 – catavaran 2015-02-10 01:18:43

+0

謝謝,補充... – 2015-02-10 01:23:53

回答

3

您可以使用{% for %} ... {% empty %}模板標籤。

{% for location in locations %} 
    {% for image in location.locationimage_set.all %} 
     ... 
    {% empty %} 
     {# there is no images for `location` #} 
     {% ifequal location.locationtype 'region' %} 
      {% for city in location.location_region.all %} 
       {% for image in city.locationimage_set.all %} 
        ... 
       {% endfor %} 
      {% endfor %} 
     {% endifequal %} 
    {% endfor %} 
{% endfor %} 

但我認爲這是太複雜的模板代碼。可能是將get_images()方法添加到Location模型並在python中實現此邏輯會更好嗎?

class Location(models.Model): 

    def get_images(self): 
     images = self.locationimage_set.all() 
     if self.locationtype == 'region' and not images: 
      images = LocationImage.objects.filter(location__region=self) 
     return images 

該方法比模板版本更有效率。模板將如此簡單:

{% for location in locations %} 
    {% for image in location.get_images %} 
     ... 
    {% endfor %} 
{% endfor %} 
+0

謝謝,這真棒!我去了get_images方法,並工作。採取了一些重新調整我的代碼來匹配,但效果很好! – 2015-02-10 03:03:42