我正在学习Django,因为我不知道该搜索什么,所以我找不到一个简单的答案。
我有一个名为NFLteam
的类/表,一旦为NFL中的每个团队填充一个条目,就永远不会改变。我把它作为一个数据库表,所以我可以在另一个表中指向特定NFL团队的外键。现在团队只有一个字段,一个名字。但是将来他们会有更多。
来自models.py
class NFLteam( models.Model ):
team_name = models.CharField( max_length=3, choices=NFL_TEAMS )
def __unicode__( self ):
return self.team_name
以下是上面引用的NFL_TEAMS
序列:
NFL_TEAMS = (
( 'ARI', 'Arizona Cardinals' ),
( 'ATL', 'Atlanta Falcons' ),
( 'BAL', 'Baltimore Ravens' ),
( 'BUF', 'Buffalo Bills' ),
( 'CAR', 'Carolina Panthers' ),
( 'CHI', 'Chicago Bears' ),
( 'CIN', 'Cincinnati Bengals' ),
( 'CLE', 'Cleveland Browns' ),
( 'DAL', 'Dallas Cowboys' ),
( 'DEN', 'Denver Broncos' ),
( 'DET', 'Detroit Lions' ),
( 'GB' , 'Green Bay Packers' ),
( 'HOU', 'Houston Texans' ),
( 'IND', 'Indianapolis Colts' ),
( 'JAX', 'Jacksonville Jaguars' ),
( 'KC' , 'Kansas City Chiefs' ),
( 'MIA', 'Miami Dolphins' ),
( 'MIN', 'Minnesota Vikings' ),
( 'NE' , 'New England Patriots' ),
( 'NO' , 'New Orleans Saints' ),
( 'NYG', 'New York Giants' ),
( 'NYJ', 'New York Jets' ),
( 'OAK', 'Oakland Raiders' ),
( 'PHI', 'Philadelphia Eagles' ),
( 'PIT', 'Pittsburgh Steelers' ),
( 'SD' , 'San Diego Chargers' ),
( 'SEA', 'Seattle Seahawks' ),
( 'SF' , 'San Francisco 49ers' ),
( 'STL', 'Saint Louis Rams' ),
( 'TB' , 'Tampa Bay Buccaneers' ),
( 'TEN', 'Tennessee Titans' ),
( 'WAS', 'Washington Redskins' ),
)
由于NFLteam
表永远不会改变(或者很少,很少),有没有办法让它最终化或不可变,这样模型就会拒绝接受它的更新?理想情况下,我希望这与DB无关,因此它与SQLite,MySql等一样(如Django模型定义)。
答案 0 :(得分:2)
我会这样做:
class NonUpdateAbleModelMixin():
def save(self, *args, **kwargs):
pass
class NFLteam(models.Model, NonUpdateAbleModelMixin):
team_name = models.CharField( max_length=3, choices=NFL_TEAMS )
def __unicode__( self ):
return self.team_name
在save
内,您可以使用设置中的某些标记或任何您想要的标记
答案 1 :(得分:1)
您可以在设置中的某处添加标记,然后覆盖该类的保存功能,如果该标志打开则返回。
from django.conf import settings
...
class NFLTeam(models.Model):
...
def save(self, *args, **kwargs):
if settings.NFL_NO_SAVE is True:
return