Home > Software design >  Add unique_together validation check on internal attirbutes of JSONField
Add unique_together validation check on internal attirbutes of JSONField

Time:07-18

I am using following model.

class MyProfile(models.Model):
    name = models.CharField(max_length=100, default=None)
    account_id = models.CharField(max_length=64, default=None)
    prof_config = JSONField(null=True, blank=True, default=None)
    result = JSONField(null=True, blank=True, default=None)

    class Meta(object):
        app_label = "app"
        verbose_name = "MyProfile"
        unique_together = [["account_id", "prof_config"]]

Previously prof_config included:

prof_config =  {"username":"pranav","password":"123456"}

But now I have changed it to :

prof_config =  {"username":"pranav","password":"123456","last_sync_time":null}

And as I want unique_together validation only on account_id, username and password. For that I changed unique_together to:

 unique_together = [["account_id", "prof_config__username","prof_config__password"]]

But it didn't work. It gave me following error (if last sync time is null for both profiles):

"Error while creating My Profile, error:duplicate key value violates unique 
constraint \"app_myprofile_account_id_prof_config_b94a5cdc_uniq\"\nDETAIL:  Key 
(account_id, prof_config)=(4, {\"password\": \"123456\", \"username\": \"pranav\", 
\"last_sync_time\": null}) already exists.\n", "causality": "", "opid": "fc3501fa", 
"opid_chain": "fc3501fa", "level": "ERROR"}

I am getting this error even after I have added unique_together for account_id, username and password ([["account_id", "prof_config__username","prof_config__password"]]). But it's still taking whole prof_config. And If last sync time is different the profile is being created.

So Is there any way to do this.

CodePudding user response:

You can override clean method in ModelForm and do manual validation

def clean(self):
    cleaned_data = self.cleaned_data
    # Your custom validation
    ...

    # raise error if something is not right
    raise ValidationError('Error')

    return cleaned_data

CodePudding user response:

The error that you ran into is related to the existing data in your database, The error is saying you have already data in the database that doesn't follow your new unique_together rule

You should find and remove/edit the specific record that caused this error

  • Related