arcee123
arcee123

Reputation: 243

how to make django's choice option dynamic in the model

I am creating a reference lexicon in django. The lexicon is a translator for certain fields from one language to another.

The lexicon goes like this: 'id','lng1','lng2','lng3' I have a model that uses the lexicon in one of the fields.

class lexicon(models.Model):
    lng1 = model.Charfield(max_length=255)
    lng2 = model.Charfield(max_length=255)
    lng3 = model.Charfield(max_length=255)

lexicon_choices = (
  (lng1=lng1),
  (lng2=lng2),
  (lng3=lng3)
)


class model(models:Model):
    model_name = model.Charfield(max_length=255, unique)
    field1 = model.Charfield(max_length=3,CHOICES=lexicon_choices)

This works ok, but I want to know, is there a way to glean out the column names from class lexicon and port them as the choices for class model? I am using Django Rest Framework for the first time, and I want to make sure the right lng is there.

Thanks

Upvotes: 0

Views: 1480

Answers (2)

doniyor
doniyor

Reputation: 37934

yes, possible. but in admin.py

class CustomForm(forms.ModelForm):
    class Meta:
        model = YourModel

    def __init__(self, *args, **kwargs):
        super(CustomForm, self).__init__(*args, **kwargs)
        choices = [(x.id, x.name) for x in Lexicon.objects.all()]
        self.fields['field1'].choices = choices

class YourModelAdmin(admin.ModelAdmin):
    form = CustomForm

and your original model looks like:

class YourModel(models:Model):
    model_name = model.Charfield(max_length=255, unique)
    field1 = models.CharField(max_length=10, choices=(('--', '--'),))

IMPORTANT: do not name your class names with lower case. ;)

Upvotes: 2

masnun
masnun

Reputation: 11916

You can use a ForeignKey on the lexicon class to your main model. This will ensure a One to Many relationship. And you can store the values in database.

Upvotes: 1

Related Questions