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()
通过重写^{} method 并检查每个收音机是否只有六个电台来实现这一点。如果正在添加第七个工作站,则可以通过相应的错误消息中止保存。在
在这种情况下,您可以用一个实例(类似于单音)创建一个无线电模型,并创建6个电台作为一对一字段。请看可能的决定。在
其优点是可以对每个站点进行随机访问。没有更多的检查了。在
相关问题 更多 >
编程相关推荐