django完整性错误,关系多对多

时间:2012-07-07 01:16:26

标签: python django referential-integrity integrity database-integrity

那是我的models.py:

class User(models.Model):
    email = models.EmailField()

    def __unicode__(self):
        return str(self.email)


class Link(models.Model):
    link = models.URLField()
    users = models.ManyToManyField(User, through='ShortURL')


class ShortURL(models.Model):
    link = models.ForeignKey(Link)
    user = models.ForeignKey(User)
    short_end = models.CharField(max_length=20)
    counter = models.IntegerField() 

添加用户的工作正常:

>>> user = User.objects.create("john_doe@planetearth.com")

当我尝试添加链接时出现完整性错误:

>>> link = Link.objects.create("stackoverflow.com")
IntegrityError: shortener_link.short_end may not be NULL

我错过了什么?

1 个答案:

答案 0 :(得分:0)

您需要创建一个这样的链接:

Link.objects.create(link="stackoverflow.com", user = request.user, short_end = 'stack', counter = 0)

因为所有这些字段都是必需的。