[Answered ]-Django Arrayfield with referential constraint for postgres

2đź‘Ť

âś…

Unfortunately in Postgres 9.3, you won’t be able to add a foreign key constraint on the array field. See this answer for more details.

However, you can perform some level of validation within Django models, for example:

class Info(models.Model):        
    ...
    def save(self, *args, **kwargs):
        # validate all multiChoice belong in lookup
        lookup_id_list = Lookup.objects.filter(id__in=self.multiChoice)\
            .values_list('id', flat=True)
        assert set(lookup_id_list) == set(self.multiChoice)
        super(Info, self).save(*args, **kwargs)

Note that this won’t prevent someone from creating/updating Info records in the database directly which violate your “constraint”.

If your models are in a many-to-many relationship, the correct solution would be to use a ManyToMany field which can guarantee your constraint will not be violated.

👤Derek Kwok

0đź‘Ť

Thanks for the help @Derek Kwok. I did somthing similar on the Resource hydrate method.

def hydrate(self,bundle):
    #Get the array values from the request bundle eg: "{1,2,3}"
    multiChoiceValues=bundle.data['multiChoice'][1:-1].split(',')
    #Get the lookup table values from DB
    lookupObjs=Lookup.objects.all()
    
    #Compare them
    #todo: Improve loop comparisons
    for multiChoice in multiChoiceValues:
        found=False
        for objs in lookupObjs:
            if (multiChoice==''+repr(objs.id)):
                found=True
                break
        if (found==False):
            #Raise an error if any of the values passed break the referential constraint
            raise IntegrityError
    return bundle

Leave a comment