'Limit Choices for Charfield
I have a model for all choices in program. Instead of Choices Tuple , i wanna use this table for showing options and validate from table when it's gonna save. So it's not gonna be static as tuple choices in model.
class FIELD_CHOICES(models.Model):
groupName = models.CharField(max_length=120, null=True, blank=True)
value = models.CharField(max_length=120, null=True, blank=True)
key = models.CharField(max_length=120, null=True, blank=True)
active = models.BooleanField(default=True, blank=True)
Main problem is , i'm using charfield for choices right now and it should stay as charfield for other reasons. So i can't use Foreing key model type and limit_choices_to option. There are Also a lot of choices field in program so overriding save method is not best practice in this situation.
Is there any option to keep it as charfield and validate from another table ? A custom model field or anything else ?
Solution 1:[1]
You can't use
x = models.CharField( choices=someething_dynamic, ...)
because in that context, choices is a database constraint (stored in the DB, changeable only by creating and applying a migration)
You can use dynamic choices in a form that inputs data to be stored in that field. This answer, for example. The implication is that it's possible for data that isn't a valid choice to get into the database, for example by creating and saving an object with invalid data rather than acquiring the data through a form ... but then, it might in any case become invalid at a later date when the dynamic choice criteria change.
You could go further and apply the dynamic choices check in the model save process, by specifying a custom validator for the field in question.
x = models.CharField( validators=[x_validator,], ...)
Be aware that if you do this and the criteria checked by x_validator change dynamically, you may have to handle ValidationError arising when you update an object which was saved with a value which was valid when it was created, but which is no longer valid!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nigel222 |
