3

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

4

2 回答 2

4

You implement this by overriding the save method and checking that for each radio there are only six stations. If the seventh station is being added, you can abort the save with an appropriate error message.

于 2012-09-03T08:39:20.263 回答
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()
于 2012-09-04T10:03:32.520 回答