django model (models.E012) 'unique_together' refers to the non-existent field

本文介绍了一个在使用Django model建表时遇到的独特问题,即'unique_together'属性引用了不存在的字段。文章详细说明了如何通过正确定义字段实例来解决此问题。

    今天,在使用django model建表的过程中,遇到一个诡异的bug,django一直给我提示(models.E012) 'unique_together' refers to the non-existent field。我一直没明白,错误代码如下

class Test(models.Model):
    index = models.IntegerField
    score = models.IntegerField

    class Meta:
        unique_together = ('index', 'score')

    经过多次调试,发现删除meta能够建表,加上meta就报错。原因在于这时的index和score是一个字段类,在meta中,Django检测并枚举字段实例(即通过运行isinstance(v, Field))来创建字段。因此,在这种情况下,无法使用meta。我们只需加上一对括号,index和score就变成了字段实例,就能正确运行了。正确的代码如下:

class Test(models.Model):
    index = models.IntegerField()
    score = models.IntegerField()

    class Meta:
        unique_together = ('index', 'score')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值