Question

Here are my models:

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')

I want the field no_celex to be unique ONLY if it "comes from" index_ids. How to do that?

More explanation :

This must be impossible:

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

But this can be possible:

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

And this can be possible too:

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

Here is my (pseudo) code so far:

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

My problem: how can I get the id of the current act (from my ActIds model)? It is an update form...

Was it helpful?

Solution

Have you considered writing your own save and clean methods on your model, to enforce the logic you want?

Have your save method call full clean (which will call your custom clean).

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top