限制模型的记录数

时间:2012-09-03 08:24:16

标签: python django

我正在编写一个django模型,我想限制它的记录数量,而不是数据库中存在的记录数量。 例如,假设我有一台收音机,它可以有6个不同的可配置站 - 限制数据库中站数的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

您可以通过覆盖save method并检查每个无线电只有六个电台来实现此目的。如果正在添加第七个站,则可以使用相应的错误消息中止保存。

答案 1 :(得分:0)

在这种情况下,您可以创建一个具有单个实例(单线程)的无线电模型,并创建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()