2012-09-03 46 views
3

我正在寫一個django模型,我想限制它的記錄數量超過數據庫中可以存在的數量。 例如,假設我有一臺收音機,它可以有6個不同的可配置電臺 - 限制數據庫中電臺數量的最佳方法是什麼?模型的記錄數量限制

+2

我不認爲每個數據庫後端都有行限制功能,但爲什麼你要在db級別上使用這個功能呢?使用該程序的人是否直接訪問數據庫?爲什麼不能使用模型保存或表單保存功能來處理限制? –

+0

一個問題要澄清一下:你想要一個永久號碼的電臺還是用戶可以配置這個號碼? – sergzach

+0

永久性號碼,不可配置。 –

回答

4

您通過覆蓋save method並檢查每個無線電只有6個電臺來實現此目的。如果正在添加第七個工作站,則可以用適當的錯誤消息中止保存。

+0

我是否正確理解,如果是這樣,我們必須做一個額外的'選擇'來確定計數是否正確? – sergzach

0

在這種情況下,您可以創建一個具有單個實例的無線電模型(類似singletone)並創建6個工作站作爲一對一的字段。請參閱可能的決定。

好處是你可以有隨機訪問到每個站。沒有更多的檢查。

class RadioHasNotStationError(Exception): 
    pass 

class _Station(models.Model): # private model, so, you can't use the class anywhere else 
    # fields of station 

class Radio(models.Model): 
    station1 = models.OneToOneField(_Station) 
    station2 = models.OneToOneField(_Station) 
    station3 = models.OneToOneField(_Station) 
    station4 = models.OneToOneField(_Station) 
    station5 = models.OneToOneField(_Station) 
    station6 = models.OneToOneField(_Station) 

    def set_station(self, num, val): 
     try: 
      setattr(self, 'station{0}'.format(num), val) 
     except AttributeError: 
      raise RadioHasNotStationError("The radio has not station {0}".format(num)) 

    def get_station(self, num): 
     try: 
      result = getattr(self, 'station{0}'.format(num)) 
     except AttributeError: 
      raise RadioHasNotStationError("The radio has not station {0}".format(num)) 
    ... 
    @staticmethod 
    def get_inst(): 
     try: 
      result = Radio.objects.select_related().get(id = 1) 
     except Radio.DoesNotExist: 
      result = Radio.create() 
     return result 

radio = Radio.get_inst() 
radio.station1 = new_station 
# ... 
radio.set_station(5, new_station2) 
# ... 
station4 = radio.get_station(4) 
# ... 
radio.save()