我在SO上看到了一些类似的问题,但似乎没有人回答我的特殊问题.我是Django的新手,并且正在通过此页面上的说明指导自己,以允许自己使用自然键来加载灯具.然而,我得到反序列化错误,因为Django想要一个外键的整数,并且似乎无法将我的自然键映射到整数主键,如说明中所述.具体来说,我的相关模型代码是:
class GraphTypeManager(models.Manager):
def get_by_natural_key(self, type):
return self.get(type=type)
class GraphType(models.Model):
type = models.CharField(max_length=100, unique=True)
class GraphManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class Graph(models.Model):
name = models.CharField(max_length=200, unique=True)
type = models.ForeignKey(GraphType)
class LineManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class Line(models.Model):
name = models.CharField(max_length=200, unique=True)
class GraphToLineManager(models.Manager):
def get_by_natural_key(self, line, graph):
return self.get(line=line,graph=graph)
class GraphToLine(models.Model):
line = models.ForeignKey(Line)
graph = models.ForeignKey(Graph)
class Meta:
unique_together = (('line', "graph"),)
Run Code Online (Sandbox Code Playgroud)
我的YAML夹具是:
- model: graphs_container.GraphType
pk: null
fields:
type: TimeSeries
- model: graphs_container.Graph
pk: …Run Code Online (Sandbox Code Playgroud) 我正在开发一个系统,利用国家ID"识别记录"是一个好主意,在所有表中嵌入nat_id,使查询更容易?这样做有什么缺点?我只想在这里得到人们的意见,因为我可能会错过重要的事情.
我有一张记录许可证使用情况的表格.每个许可证使用都需要与用户和主机相关联.表定义如下所示.
create table if not exists per_user_fact
(
per_user_fact_id int unsigned not null auto_increment,
time_of_day char(16) not null,
license_served_id smallint unsigned not null,
license_hours numeric(10,2) not null,
role_name varchar(64) null,
user varchar(128) not null,
host varchar(128) not null,
primary key (per_user_fact_id),
foreign key (license_served_id) references served_license(served_license_id),
foreign key (user, host) references user_host(username, hostname)
);
Run Code Online (Sandbox Code Playgroud)
我想规范化这个表,以便将重复的用户/主机值移动到这样的新表.
create table if not exists user_host
(
username varchar(64) not null,
hostname varchar(128) not null,
primary key (username, hostname)
);
Run Code Online (Sandbox Code Playgroud)
对于user_host表,我应该选择哪种主键 - 自然或代理?我可以想到以下控制因素. …
据我所知,自然键的纯粹主义者和代理键的纯粹主义者之间正在发生战争.喜欢这个帖子(有更多)人们说'自然键对你不好,总是使用代理...
但是,无论是我是愚蠢还是盲目,但我总是看不到有代理钥匙的理由!
假设您在配置中有3个表,如下所示: 
为什么我需要一个代理键?我的意思是没有它是完全合理的.
此外,有人可以解释为什么主键不应该根据代理键纯粹主义者改变?我的意思是,如果我说color_id VARCHAR(30)了一把钥匙black,并且我不再需要黑色,因为我正在改变它charcoal,为什么改变black键charcoal和所有引用列也是一个坏主意?
编辑:刚刚注意到我甚至不需要改变它!只需创建一个新的,更改引用列(与我将使用代理键相同)并保持旧的安全....
在代理关键口头禅我需要创建额外的条目,比如id=232和name=black.这对我有什么好处?我在表中有一个备用钥匙,我不再需要了.另外我需要加入才能得到一个颜色名称,否则我可以留在一张桌子上并且快乐吗?
请向5岁的人解释一下,请记住,我并不是说"代理关键是不好的",我试图理解为什么会有人说'总是使用代理键!'.
natural-key ×4
sql ×2
django ×1
fixtures ×1
join ×1
lookup ×1
postgresql ×1
primary-key ×1
python ×1
rdbms ×1
yaml ×1