Hub*_*bro 2 mysql django model key unique
我希望我的ip和stream_id组合是独一无二的,所以我写了这个模型:
# Votes
class Vote(models.Model):
# The stream that got voted
stream = models.ForeignKey(Stream)
# The IP adress of the voter
ip = models.CharField(max_length = 15)
vote = models.BooleanField()
unique_together = (("stream", "ip"),)
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,它产生了这个表,跳过了 ip
mysql> SHOW CREATE TABLE website_vote;
+--------------+---------------------------------------------+
| Table | Create Table |
+--------------+---------------------------------------------+
| website_vote | CREATE TABLE `website_vote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stream_id` int(11) NOT NULL,
`ip` varchar(15) NOT NULL,
`vote` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `website_vote_7371fd6` (`stream_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+--------------+---------------------------------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
为什么它不包含ip在钥匙中?为了记录,我知道unique_together可以在不嵌套元组的情况下编写该行,但这与该问题无关
unique_together需要在模型Meta类中.查看文档.
class Vote(models.Model):
# The stream that got voted
stream = models.ForeignKey(Stream)
# The IP adress of the voter
ip = models.CharField(max_length = 15)
vote = models.BooleanField()
class Meta:
unique_together = (("stream", "ip"),)
Run Code Online (Sandbox Code Playgroud)
此外,还有一个内置的IPAddressField模型字段.请参阅此处的文档.