限制mod的记录数

2024-04-25 04:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: django方法模型数据库数量记录电台收音机
2条回答

通过重写^{} method并检查每个收音机是否只有六个电台来实现这一点。如果正在添加第七个工作站,则可以通过相应的错误消息中止保存。在

在这种情况下,您可以用一个实例(类似于单音)创建一个无线电模型,并创建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()

相关问题 更多 >