0

这是我的模型:

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只有在它“来自”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 模型)?这是一个更新表格...

4

1 回答 1

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)
于 2013-10-21T01:26:27.400 回答