【问题标题】:Why Unique together is not preventing non unique values?为什么Unique together 不会阻止非唯一值?
【发布时间】:2023-04-05 14:20:01
【问题描述】:

在我的模型中,2 个字段(公司、AM)的组合应该是唯一的

class Vendor_AM(models.Model):
    version = IntegerVersionField( )
    company = models.ForeignKey(V_Company, on_delete=models.PROTECT)
    AM = models.ForeignKey(AM, on_delete=models.PROTECT)
    recomendedprice = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
    price = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
    is_active = models.BooleanField(default=True)
    def __unicode__(self):
        return u'%s %s %s' % ( self.id, self.AM.material.name , self.company.name )

    class Meta:
        unique_together = (("AM", "company"),)

因此,我在 Meta 类中定义了它。但是,我在保存时收到错误消息,而不是表单验证警告。可能是什么原因?

/vendor/manufacture_material/new/1/http://127.0.0.1:8000/vendor/company/company_am_details/1// 处的 IntegrityError AM_id、company_id 列不是唯一的

更新: 表格:

class Vendor_AMForm(forms.ModelForm):

    class Meta:
        model = Vendor_AM
        fields = [ 'AM','recomendedprice','is_active' ]

我正在视图中直接填充公司。

【问题讨论】:

  • 您如何验证这一点?你的表单是什么样子的?
  • 您是否正确迁移数据库?
  • 我没有在表单中进行验证。我假设我是否有唯一的一起验证。

标签: django


【解决方案1】:

表单只能在它实际包含的字段上进行验证。由于您已从表单中排除 company,因此无法验证公司和 AM 的组合。

【讨论】:

  • 谢谢。当您询问表格时,我开始考虑它。在视图中保存以捕获它时添加了“except IntegrityError”。
猜你喜欢
  • 2011-05-25
  • 2010-10-16
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多