Amir Rachum
Amir Rachum

Reputation: 79735

Limit number of records for a model

I'm writing a django model and I would like to limit the number of records of it than can exist in the database. For example, let's say I have a radio and it can have 6 different configurable stations - what is the best way to limit the number of stations in the database?

Upvotes: 3

Views: 966

Answers (2)

sergzach
sergzach

Reputation: 6764

In this case you can create one radio model with a single instance (singletone-like) and create 6 stations as one-to-one fields. Please see the possible decision.

The advantage is you can have random access to each station. There are no any more checkings.

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()

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174758

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.

Upvotes: 4

Related Questions