这是我的模型:
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 模型)?这是一个更新表格...