2012-05-30 167 views
5
class Beverage(models.Model): 
    name=models.CharField(max_length=255) 

    def __unicode__(self): 
     return self.name 

class Location(models.Model): 
    name=models.CharField(max_length=255) 
    beverages = models.ManyToManyField(Beverage, through='LocationStandard') 
    location_number=models.CharField(max_length=255) 
    organization=models.CharField(max_length=255) 

    def __unicode__(self): 
     return self.name 

class LocationStandard(models.Model): 
    beverage=models.ForeignKey(Beverage) 
    location=models.ForeignKey(Location) #elim this or m2m 
    start_units=models.IntegerField() 
    fill_to_standard=models.IntegerField(max_length=10) 
    order_when_below=models.IntegerField(max_length=10) 

class Order(models.Model): 
    location=models.ForeignKey(Location) #elim this or m2m 
    beverage=models.ForeignKey(Beverage) 
    units_ordered=models.IntegerField(max_length=10, default=0) 
    order_delivered=models.BooleanField(default=False) 
    timestamp=models.DateTimeField(auto_now_add=True) 
    user=models.ForeignKey(User) 

如何生成一份報告,該報告將爲我提供一個HTML表格,其中包含x軸上的所有位置以及y軸上的所有飲料。我正在努力的主要事情是什麼來查詢我可以通過我可以循環的模板。思考?Django創建報告

+0

我遇到了類似的,但稍微簡單一些的場景,我需要在Y上的日期和在X上的類別。解決它與一些相當殘酷的數據傳輸。 +1,有興趣看看是否有一個好的解決方案。 – Endophage

+0

順便說一句@jasongonzales,你在哥倫比亞大學工作嗎? –

+0

不在哥倫比亞,好笑,你爲什麼問? – jasongonzales

回答

2

你不能讓他們在一個查詢中,但是你可以讓類似的東西(不想建立一個整體ENV測試,所以用它作爲線索,而不是一個有效的解決方案):

# you can't do order_by in a template, either do them in the view, or 
# make methods in the model, or make it the Meta default ordering 

# print the header, and make sure we got a list of all beverage cached 
beverages = Beverage.objects.order_by('name') 
for beverage in beverages: 
    print each cell of your header 

# print a row for each location 
locations = Location.objects.all() 
for location in locations: 
    print the location name table cell 
    location_beverages = iter(location.beverages.order_by('name')) 
    # for each beverage, we print a cell. If the beverage is in the 
    # location beverage list, we print a checked cell 
    # we use the fact that queryset are iterable to move the cursor 
    # only when there is a match 
    cur_bev = location_beverages.next() 
    for beverage in beverages: 
     if beverage == cur_bev: 
      print checked table cell 
      cur_bev = location_beverages.next() 
     else: 
      print empty table cell 

存儲查詢集的中間變量非常重要,因爲它們允許您從Django查詢集緩存中受益。

使用Django 1.4以上,可以更換:

locations = Location.objects.all() 

通過:

locations = Location.objects.prefetch_related('beverages') 

爲了得到一個嚴肅的PERF提升。

+0

所以,只需要清楚,因爲我正在寫一個Django模板,所以我可能應該將這些值替換爲一個字典,而不是實際打印它們,是的? – jasongonzales

+0

除了.order_by('name')',你可以在模板中完成所有這些。只需鬆開括號並使用{{value}}在HTML代碼中打印一個值。 –