[Answered ]-How to automatically choose related model using field value

1👍

One idea is to add choices to the BaseModel to have a string representation of your boolean value. If you set the strings equal to the A and B model names, you can use the model.get_foo_display() method to return the name of the model. Then use the Python getattr() method to access attributes as variables.

class BaseModel(models.Model):

    base_model_choices = (
        (True, 'A'),
        (False, 'B'),
    )

    is_a = models.BooleanField(choices=base_model_choices)

For example,

base = BaseModel.objects.get(id=1)
queryset = base.getattr(models, get_is_a_display()).all()
obj = getattr(models, get_is_a_display()).objects.create(base=base)
👤yagus

Leave a comment