开发者

Django database model "unique_together" not working?

I want my ip and stream_id combination to be unique, so I wrote this model:

# 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"),)

But for some reason it produces this table, skipping the 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)

Why doesn't it include ip in the key? For the record I am aware that the unique_together line can be written without nesting the tuples, but that has no bearing on the issue


unique_together needs to be in the models Meta class. See docs.

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"),)

Also, there's a builtin IPAddressField model field. See the docs here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜