2011-05-20 15 views
0

可能重複:
Unique BooleanField value in Django?如何強制執行該對象只有一個布爾型attr設置爲true?

在照片模式我想選擇它作爲是列出多個畫廊頁面上的畫廊封面圖片的照片。

我寫了下面的代碼,但它看起來像香港專業教育學院創建了一個循環

class Photograph(models.Model): 
    project = models.ForeignKey(Project) 
    description = models.TextField(max_length=5000, default=False) 
    image = models.ImageField(upload_to="photographs/") 
    thumb = models.ImageField(upload_to="photographs/", blank=True, help_text="Ignore this field, it will autopopulate") 
    thumbnail = models.CharField(max_length=250, blank=True) 
    filename = models.CharField(max_length=100, default=False, help_text="Ignore this field, it will autopopulate") 
    portfolio_image = models.BooleanField(default=False, help_text="Do you want this image to appear as the portfolio image?") 
    date_added = models.DateTimeField('date published') 

def save(self): 
    # get filename for use later 
    filename, extension = os.path.splitext(self.image.name) 
    self.filename = slugify(filename) 
    self.thumbnail = filename+"-t.jpg" 

    # is this the testimonial image, if so, unselect other images 
    if self.testimonial_image is True: 
     others = Photograph.objects.filter(project=self.project).filter(testimonial_image=True) 
     pdb.set_trace() 
     for o in others: 
      o.testimonial_image = False 
      o.save() 

什麼heppening是

  • 上傳一張圖片,將其設置爲 portfolio_image
  • 代碼貫穿而過點擊if語句
  • 填充他人,進入o.save()並最終運行完全相同我已經定義了210個代碼。

looped!

我該如何解決這個問題?

+0

'testimonial_image'定義在哪裏? – 2011-05-20 13:10:38

+0

也應該在模型中將'thumb'和'filename'設置爲'editable = False',或者將它們從表單中排除,而不是向用戶陳述它們將被自動填充 – 2011-05-20 13:19:55

+0

用於測試目的。會現在編輯問題,刪除錯誤的,我得到了這個模型 – bytejunkie 2011-05-20 13:29:46

回答

2

我認爲你應該在其他地方存儲testimonial_image,它應該等於id所需的Photograph對象。

+0

好主意的證言和portflio圖像。與其給每張照片分配一個數據點,儘管它們中的大多數都是錯誤的,但您可以有一個只有2列的小表格,一張專輯的外鍵和一個封面鏡頭的外鍵。 – 2011-05-20 13:17:22

+0

我寧願用戶能夠上傳圖像,並在當時設置attr。 – bytejunkie 2011-05-20 13:30:11

+0

這並不意味着您應該爲任何照片存儲此標誌。將它存儲在另一個表中(例如j_syk建議的那樣),並將其設置在'save()'中。那就是你想要的。 – DrTyrsa 2011-05-20 13:46:19

相關問題