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.
0👍
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()
- [Django]-Django Testing – I only want one of my databases created – how to specify
- [Django]-Empty label in widget Select
- [Django]-Property decorator eager load and eager load in general using Django
- [Django]-Django-admin.py makemessages does not create .po files
- [Django]-Django: Serialize queryset and include one-to-many relationship children
Source:stackexchange.com