唯一性仅取决于一对一的关系

时间:2013-10-20 17:27:44

标签: django field unique relationship one-to-one

以下是我的模特:

class ActIds(models.Model):
    #no_celex for index_ids must be unique
    no_celex=models.CharField(max_length=15, blank=True, null=True)

class Act(models.Model):
    index_ids=models.OneToOneField(ActIds, related_name='index_ids')
    eurlex_ids=models.OneToOneField(ActIds, related_name='eurlex_ids')
    oeil_ids=models.OneToOneField(ActIds, related_name='oeil_ids')

我希望字段no_celex只有 ONLY ,如果它来自“index_ids”。怎么做?

更多解释

必须不可能

act=Act()
act.index_ids.no_celex="test"
act.save()
act2=Act()
act2.index_ids.no_celex="test"
act2.save()

但这可能可能

act=Act()
act.index_ids.no_celex="test"
act.eurlex_ids.no_celex="test"
act.save()

这也可能可能

act=Act()
act.index_ids.no_celex="test"
act.save()
act2=Act()
act2.eurlex_ids.no_celex="test"
act2.save()

到目前为止,这是我的(伪)代码:

class ActIdsForm(forms.ModelForm):
    class Meta:
        model=ActIds

    def is_valid(self):
        valid=super(ActIdsForm, self).is_valid()

        if not valid:
            return valid

        no_celex=self.cleaned_data.get("no_celex")

        try:
            #does the no_celex already exist? 
            act=Act.objects.get(index_ids.no_celex=no_celex)
            #if yes, is it the act being saved (ok) or another act (error)?
            if act.index_ids.id!="id of the act being saved":
                print "pb no_celex already exists"
                self._errors['no_celex']=ErrorList([u"no_celex already exists!"])
                return False
    except:
                pass

        return True

我的问题:如何获取当前行为的id(来自我的ActIds模型)?这是一个更新表格......

1 个答案:

答案 0 :(得分:1)

您是否考虑在模型上编写自己的保存和清理方法,以强制执行您想要的逻辑?

让您的保存方法调用完全干净(这将调用您的自定义清理)。

def clean(self):
    # check for stuff to help with conditions
    if <my conditions are not met>:
        raise ValidationError('%s is not a valid Model. Please follow the rules')   

def save(self, *args, **kwargs):
    self.full_clean()
    super(MyModel, self).save(*args, **kwargs)